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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bd5912fe2c5c37658f28f6b159b39645 | Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too. | ['implementation', 'greedy', 'strings'] | s = input()
k = int(input())
t = frozenset(s)
if len(s) < k:
print("impossible")
exit()
print(max(k - len(t), 0)) | Python | [
"strings"
] | 286 | 121 | 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,686 |
d4d41e75c68ce5e94c92e1b9876891bf | Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.Consider the 2D plane. There is a token which is initially at (0,0). In one move a player must increase either the x coordinate or the y coordinate of the token by exactly k. In doing so, the player must ensure that the token stays within a (Euclidean) distance d from (0,0).In other words, if after a move the coordinates of the token are (p,q), then p^2 + q^2 \leq d^2 must hold.The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win. | ['geometry', 'games', 'math'] | t = int(input())
for i in range(t):
n,k=map(int,input().split())
x = int((n / k)/2**0.5)
a = (x+1)**2 + (x)**2
b = (n/k)**2
if a >b:
print('Utkarsh')
else:
print('Ashish') | Python | [
"math",
"games",
"geometry"
] | 733 | 212 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 1,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,656 |
900a509495f4f63f4fa5b66b7edd84f7 | In this problem we consider a very simplified model of Barcelona city.Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points (x, y) for which ax + by + c = 0.One can walk along streets, including the avenue. You are given two integer points A and B somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to B from A. | ['implementation', 'geometry'] | from math import ceil,floor
a,b,c = (int(e) for e in input().split(' '))
x1,y1,x2,y2 = (int(e) for e in input().split(' '))
def dist(x1,y1,x2,y2):
return ((x1-x2)**2+(y1-y2)**2)**.5
def m_dist(x1,y1,x2,y2):
return abs(x1-x2)+abs(y1-y2)
def project(x,y):
if(a==0 and b==0):return (float('inf'),float('inf'))
return ((-c*a+b*b*x-a*b*y)/(a*a+b*b),(-a*b*x+a*a*y-b*c)/(a*a+b*b))
def x_to_y(x):
if(b==0):return float('inf')
return (-c-a*x)/b
def y_to_x(y):
if(a==0):return float('inf')
return (-c-b*y)/a
point1x,point1y = project(x1,y1)
point1s = []
t = ceil(point1x)
point1s.append((t,x_to_y(t)))
t = floor(point1x)
point1s.append((t,x_to_y(t)))
t = ceil(point1y)
point1s.append((y_to_x(t),t))
t = floor(point1y)
point1s.append((y_to_x(t),t))
point1s.append((y_to_x(y1),y1))
point1s.append((x1,x_to_y(x1)))
point2x,point2y = project(x2,y2)
point2s = []
t = ceil(point2x)
point2s.append((t,x_to_y(t)))
t = floor(point2x)
point2s.append((t,x_to_y(t)))
t = ceil(point2y)
point2s.append((y_to_x(t),t))
t = floor(point2y)
point2s.append((y_to_x(t),t))
point2s.append((y_to_x(y2),y2))
point2s.append((x2,x_to_y(x2)))
res = m_dist(x1,y1,x2,y2)
for p1 in point1s:
for p2 in point2s:
t = m_dist(x1,y1,p1[0],p1[1])
t += dist(p1[0],p1[1],p2[0],p2[1])
t += m_dist(x2,y2,p2[0],p2[1])
# print(p1,p2,t)
if(res>t):
res = t
print(res)
# print(point1x,point1y)
# print(point2x,point2y)
| Python | [
"geometry"
] | 643 | 1,417 | 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
} | 3,246 |
0b204773f8d06362b7569bd82224b218 | We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". | ['data structures', 'constructive algorithms', '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")
MAX = 1000001
bitscount = 30
prefix_count = [[0]*(10**5+1) for i in range(30)]
def findPrefixCount(arr, n):
for i in range(0, bitscount):
prefix_count[i][0] = ((arr[0] >> i) & 1)
for j in range(1, n):
prefix_count[i][j] = ((arr[j] >> i) & 1)
prefix_count[i][j] += prefix_count[i][j - 1]
def rangeOr(l, r):
ans = 0
for i in range(bitscount):
x = 0
if (l == 0):
x = prefix_count[i][r]
else:
x = prefix_count[i][r] - prefix_count[i][l - 1]
# Condition for ith bit
# of answer to be set
if (x == r - l + 1):
ans = (ans | (1 << i))
return ans
n, m = map(int, input().split())
a = [[0] * n for i in range(30)]
query = []
for i in range(m):
l, r, q = map(int, input().split())
query.append([l-1, r-1, q])
c = bin(q)[2:][::-1]
b = []
for j in c:
b.append(int(j))
j = 0
while (j < len(b)):
if b[j] == 1:
a[j][l - 1] += 1
if r != n:
a[j][r] -= 1
j += 1
for i in range(30):
j = 1
while (j < n):
a[i][j] += a[i][j - 1]
j += 1
j = 0
while (j < n):
if a[i][j] > 0:
a[i][j] = 1
j += 1
res=[]
for i in range(n):
s = ""
j=29
while(j>=0):
s += str(a[j][i])
j+=-1
res.append(int(s,2))
findPrefixCount(res, n)
f=0
for j in query:
if rangeOr(j[0],j[1])!=j[2]:
f=1
break
if f==1:
print("NO")
else:
print("YES")
print(*res)
| Python | [
"trees"
] | 504 | 3,298 | 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
} | 619 |
f3ed9a3d4566cdb04cdc26be51027d44 | Christmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains n chocolates. The i-th chocolate has a non-negative integer type a_i.Icy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all a_i are distinct). Icy wants to make at least one pair of chocolates the same type. As a result, she asks her grandparents to perform some chocolate exchanges. Before performing any chocolate exchanges, Icy chooses two chocolates with indices x and y (1 \le x, y \le n, x \ne y).In a chocolate exchange, Icy's grandparents choose a non-negative integer k, such that 2^k \ge a_x, and change the type of the chocolate x from a_x to 2^k - a_x (that is, perform a_x := 2^k - a_x).The chocolate exchanges will be stopped only when a_x = a_y. Note that other pairs of equal chocolate types do not stop the procedure.Icy's grandparents are smart, so they would choose the sequence of chocolate exchanges that minimizes the number of exchanges needed. Since Icy likes causing trouble, she wants to maximize the minimum number of exchanges needed by choosing x and y appropriately. She wonders what is the optimal pair (x, y) such that the minimum number of exchanges needed is maximized across all possible choices of (x, y).Since Icy is not good at math, she hopes that you can help her solve the problem. | ['dfs and similar', 'dp', 'games', 'graphs', 'implementation', 'math', 'number theory', 'shortest paths', 'trees'] | from sys import *
n = int(stdin.readline())
tree = [{} for _ in range(31)]
idx, iid = {}, 0
for x in map(int, stdin.readline().split()):
iid += 1
idx[x] = iid
tree[x.bit_length()][x] = (x, 0)
x, y, m = 0, 0, 0
for i in range(30, 0, -1):
if not tree[i]:
continue
k, mp = 1 << i, tree[i]
kk = k >> 1
for a in mp:
av, ac = mp[a]
b = k - a if a > kk else 0
j = b.bit_length()
if b in tree[j]:
bv, bc = tree[j][b]
r = ac + bc + 1
if r > m:
x, y, m = av, bv, r
if ac + 1 > bc:
tree[j][b] = (av, ac + 1)
else:
tree[j][b] = (av, ac + 1)
print(idx[x], idx[y], m) | Python | [
"graphs",
"math",
"number theory",
"trees",
"games"
] | 1,486 | 763 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | {
"games": 1,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 405 |
6e2a8aa58ed8cd308cb482e4c24cbbbb | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | ['binary search', 'geometry'] | import math,sys
eps = 1e-8
n = input()
al = [map(int,raw_input().split()) for i in xrange(n+1)]
vp,vs = map(int,raw_input().split())
px,py,pz = p0 = map(int,raw_input().split())
al = [(x-px,y-py,z-pz) for x,y,z in al]
d3=lambda x,y,z:x*x+y*y+z*z
t0,ts = 0,0
rt = None
for i in range(n):
c = [y-x for x,y in zip(al[i],al[i+1])]
ll = d3(*c)
l = ll**0.5
ts+=l
te = ts/vs
v = [vs*x for x in c]
s = [l*x-a*t0 for x,a in zip(al[i],v)]
a = d3(*v)-vp*vp*ll
b = 2*sum(x*i for x,i in zip(s,v))
c = d3(*s)
d = b*b-4*a*c
fa = abs(a)<eps
f = lambda t: (t0-eps<t<te+eps)
if fa:
if abs(b)>eps and f(-c/b):
rt = -c/b
break
elif d>-eps:
if d<eps: d=0
a*=2.0
d**=0.5
tl = [t for t in ((-b+d)/a,(-b-d)/a) if f(t)]
if tl:
rt = min(tl)
break
t0 = te
if rt is None: print "NO"
else:
print "YES"
print "%.9f"%rt
print " ".join(["%.9f"%((x+a*rt)/l+p) for x,a,p in zip(s,v,p0)])
| Python | [
"geometry"
] | 1,268 | 1,036 | 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,437 |
df778e55a2c676acca7311d885f61d7a | Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, \dots, a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and rearrange the letters within each string a_i however he wants.For example, if s = baba and k=2, Phoenix may distribute the letters of his string in many ways, such as: ba and ba a and abb ab and ab aa and bb But these ways are invalid: baa and ba b and ba baba and empty string (a_i should be non-empty) Phoenix wants to distribute the letters of his string s into k strings a_1, a_2, \dots, a_k to minimize the lexicographically maximum string among them, i. e. minimize max(a_1, a_2, \dots, a_k). Help him find the optimal distribution and print the minimal possible value of max(a_1, a_2, \dots, a_k).String x is lexicographically less than string y if either x is a prefix of y and x \ne y, or there exists an index i (1 \le i \le min(|x|, |y|)) such that x_i < y_i and for every j (1 \le j < i) x_j = y_j. Here |x| denotes the length of the string x. | ['constructive algorithms', 'sortings', 'greedy', 'strings'] | from collections import defaultdict
def solve(t):
for i in range(t):
nk = input().split()
n, k = int(nk[0]), int(nk[1])
s = [x for x in input()]
d = defaultdict(int)
for i in s:
d[i] += 1
if len(d) > 1:
if d[min(d)] < k:
c = k - d.pop(min(d))
while c != 1:
d.update({min(d) : d[min(d)] - 1})
if not d[min(d)]:
d.pop(min(d)) # будет флудить ?
c -= 1
print(min(d))
elif d[min(d)] == k:
p = min(d)
d.pop(min(d))
if len(d) == 1:
print(p + min(d.keys()) * (d[min(d)]//k + (1 if d[min(d)] % k else 0)))
else:
print(p, end='')
for _ in range(len(d)):
f = min(d)
print(f * d.pop(min(d)), end='')
print()
else:
d.update({min(d) : d[min(d)] - k + 1})
for _ in range(len(d)):
f = min(d)
print(f * d.pop(min(d)), end='')
print()
else:
print(min(d.keys()) * (d[min(d)]//k + (1 if d[min(d)] % k else 0)))
solve(int(input())) | Python | [
"strings"
] | 1,377 | 1,395 | 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
} | 633 |
4df38c9b42b0f0963a121829080d3571 | There are n people participating in some contest, they start participating in x minutes intervals. That means the first participant starts at time 0, the second participant starts at time x, the third — at time 2 \cdot x, and so on.Duration of contest is t minutes for each participant, so the first participant finishes the contest at time t, the second — at time t + x, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants. | ['combinatorics', 'geometry', 'greedy', 'math'] |
def main():
test_case = int(input())
for i in range(0, test_case):
inputs = tuple(map(int, input().split()))
n = inputs[0]
x = inputs[1]
t = inputs[2]
f = t // x
if n < f:
f = n
sum = (2*n*f - f**2 - f)//2
print(f"{sum}")
if __name__ == "__main__":
main()
| Python | [
"math",
"geometry"
] | 663 | 384 | 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
} | 337 |
4b49f1b3fca4acb2f5dce25169436cc8 | Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all , and h(g(x)) = f(x) for all , or determine that finding these is impossible. | ['dsu', 'constructive algorithms', 'math'] | n = int(input())
f = [None] + list(map(int, input().split(' ')))
invalid = False
g = [None] + [0] * n
h = [None]
x_is_f_which = [None] + [0] * n
m = 0
vis = [None] + [False] * n
for i in range(1, n + 1):
x = f[i]
if f[x] != x:
invalid = True
break
if not vis[x]:
vis[x] = True
m = m + 1
h.append(x)
x_is_f_which[x] = m
if invalid:
print('-1')
else:
for i in range(1, n + 1):
g[i] = x_is_f_which[f[i]]
print(m)
def print_list(l):
print(' '.join(list(map(str, l[1:]))))
print_list(g)
print_list(h)
| Python | [
"graphs",
"math"
] | 522 | 600 | 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
} | 394 |
531746ba8d93a76d5bdf4bab67d9ba19 | Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so. | ['data structures', 'constructive algorithms', 'greedy', 'graphs'] | n = input()
flag = 0
freq = [0] * (n + 1)
for i in xrange(n - 1):
a, b = map(int, raw_input().strip().split())
if b != n:
flag = 1
break
freq[a] += 1
if flag:
print "NO"
exit()
tree = [0] * n
tree[0] = n
free = 0
freeptr = 1
fillptr = 0
for u in xrange(n - 1, 0, -1):
if freq[u] == 0:
if free <= 0:
flag = 1
break
else:
while tree[freeptr] != 0:
freeptr += 1
if freeptr >= n:
flag = 1
break
if flag: break
tree[freeptr] = u
free -= 1
while tree[freeptr] != 0:
freeptr += 1
if freeptr >= n: break
continue
fillptr += freq[u]
free += (freq[u] - 1)
if fillptr >= n:
flag = 1
break
tree[fillptr] = u
if flag:
print "NO"
else:
print "YES"
for i in xrange(n - 1):
print tree[i], tree[i + 1] | Python | [
"graphs"
] | 563 | 1,032 | 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,375 |
daabf732540e0f66d009dc211c2d7b0b | There are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where is bitwise xor operation (see notes for explanation). Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem. | ['number theory', 'brute force', 'math'] | n,x=map(int,input().split())
count = 0
d = {}
l = list(map(int,input().split()))
inp = l[0]
d[inp]=1
for i in range(1,n):
inp = l[i]
xor = x^inp
if xor in d:
count+=d[xor]
if inp not in d:
d[inp]=0
d[inp]+=1
print(count) | Python | [
"math",
"number theory"
] | 414 | 229 | 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,791 |
89e80e6c86a824a18597f28adf49a846 | This is the easy version of this problem. The only difference is the limit of n - the length of the input string. In this version, 1 \leq n \leq 2000. The hard version of this challenge is not offered in the round for the second division. Let's define a correct bracket sequence and its depth as follow: An empty string is a correct bracket sequence with depth 0. If "s" is a correct bracket sequence with depth d then "(s)" is a correct bracket sequence with depth d + 1. If "s" and "t" are both correct bracket sequences then their concatenation "st" is a correct bracket sequence with depth equal to the maximum depth of s and t. For a (not necessarily correct) bracket sequence s, we define its depth as the maximum depth of any correct bracket sequence induced by removing some characters from s (possibly zero). For example: the bracket sequence s = "())(())" has depth 2, because by removing the third character we obtain a correct bracket sequence "()(())" with depth 2.Given a string a consists of only characters '(', ')' and '?'. Consider all (not necessarily correct) bracket sequences obtained by replacing all characters '?' in a by either '(' or ')'. Calculate the sum of all the depths of all these bracket sequences. As this number can be large, find it modulo 998244353.Hacks in this problem in the first division can be done only if easy and hard versions of this problem was solved. | ['dp', 'combinatorics', 'probabilities'] | import sys
range = xrange
input = raw_input
import __pypy__
mulmod = __pypy__.intop.int_mulmod
MOD = 998244353
half = pow(2, MOD - 2, MOD)
S = input()
n = len(S)
A = []
for c in S:
if c == '?':
A.append(0)
elif c == '(':
A.append(1)
else:
A.append(2)
DPL = [[0]*(n - l + 1) for l in range(n + 1)]
DPR = [[0]*(n - l + 1) for l in range(n + 1)]
for l in range(1, n + 1):
for x in range(n - l + 1):
if A[x] == 0:
DPL[l][x] = mulmod(half, DPR[l - 1][x + 1] + DPL[l - 1][x + 1], MOD)
elif A[x] == 1:
DPL[l][x] = DPR[l - 1][x + 1]
else:
DPL[l][x] = DPL[l - 1][x + 1]
for x in range(n - l + 1):
if A[x + l - 1] == 0:
DPR[l][x] = mulmod(half, DPR[l - 1][x] + DPL[l - 1][x] + 1, MOD)
elif A[x + l - 1] == 1:
DPR[l][x] = DPR[l - 1][x]
else:
DPR[l][x] = DPL[l - 1][x] + 1
print DPL[n][0] * pow(2, sum(1 for a in A if a == 0), MOD) % MOD
| Python | [
"math",
"probabilities"
] | 1,495 | 1,005 | 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,832 |
3cdd85f86c77afd1d3b0d1e951a83635 | On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a. In other words, the value should be minimum possible.If there are many optimal solutions, Mister B should be satisfied with any of them. | ['constructive algorithms', 'geometry', 'math'] | from sys import stdin, stdout
n, a = map(int, stdin.readline().split())
ans = 180 * (n - 2) / n
f, s, t = 1, 2, 3
dif = 180 / n
cnt = dif
for i in range(n - 2):
if abs(a - ans) > abs(a - cnt):
ans = cnt
f, s, t = 2, 1, 3 + i
cnt += dif
stdout.write(str(f) + ' ' + str(s) + ' ' + str(t)) | Python | [
"math",
"geometry"
] | 611 | 320 | 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
} | 404 |
5a3bbc6668268dabb49316a1c8d4ea8c | You are given an integer m, and a list of n distinct integers between 0 and m - 1.You would like to construct a sequence satisfying the properties: Each element is an integer between 0 and m - 1, inclusive. All prefix products of the sequence modulo m are distinct. No prefix product modulo m appears as an element of the input list. The length of the sequence is maximized. Construct any sequence satisfying the properties above. | ['dp', 'graphs', 'constructive algorithms', 'number theory', 'math'] | import math
def gcdExtended(a, b):
# Base Case
if a == 0 :
return b, 0, 1
gcd, x1, y1 = gcdExtended(b%a, a)
# Update x and y using results of recursive
# call
x = y1 - (b//a) * x1
y = x1
return gcd, x, y
def rev_elem(x, m):
return (gcdExtended(x, m)[1] % m + m) % m
n, m = map(int, input().split())
a = []
if n > 0:
a = [int(i) for i in input().split()]
banned = [False] * (m + 5)
for i in a:
banned[i] = True
cycle = [[] for i in range(m + 5)]
d, dp, p = [], [], []
for i in range(m):
cycle[math.gcd(m, i)].append(i)
cycle = [[i for i in j if not banned[i]] for j in cycle]
d = [i for i in range(1, m + 1) if m % i == 0]
dp = [len(cycle[i]) for i in d]
p = [-1 for i in d]
ans, lst = -1, -1
for i in range(len(d)):
if dp[i] > ans:
ans, lst = dp[i], i
for j in range(i + 1, len(d)):
if d[j] % d[i] != 0 or dp[j] > dp[i] + len(cycle[d[j]]):
continue
dp[j] = dp[i] + len(cycle[d[j]])
p[j] = i
print(ans)
pos, dpos, pref = [], [], []
cur = lst
while cur != -1:
dpos.append(d[cur])
cur = p[cur]
dpos.reverse()
for i in dpos:
pref += cycle[i]
cur = 1
for i in pref:
ad = 1
if math.gcd(i, m) != math.gcd(cur, m):
ad = ((cur * math.gcd(i, m) // math.gcd(cur, math.gcd(i, m))) // cur) % m
ncur = (cur * ad) % m
ad *= i // math.gcd(ncur, m) * (rev_elem(ncur // math.gcd(ncur, m), m // math.gcd(ncur, m)))
ad %= m
cur = (cur * ad) % m
pos.append(ad)
print(*pos) | Python | [
"graphs",
"number theory",
"math"
] | 434 | 1,584 | 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
} | 3,949 |
32096eff277f19d227bccca1b6afc458 | A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1". | ['constructive algorithms', 'trees', 'graphs'] | def solve(n,d,h) :
if n<d+1 :
return False
if d>2*h :
return False
if d-h<0 :
return False
if d==1 and n>=3 :
return False
cnt=1
h0=d-h
for i in range(h) :
print(cnt,cnt+1)
cnt+=1
if h0 :
print(1,cnt+1)
cnt+=1
for i in range(h0-1) :
print(cnt,cnt+1)
cnt+=1
if h0 :
for i in range(n-d-1) :
print(1,cnt+1)
cnt+=1
else :
for i in range(n-d-1) :
print(2,cnt+1)
cnt+=1
return True
n,d,h=[int(i) for i in input().split()]
if not solve(n,d,h) :
print(-1) | Python | [
"graphs",
"trees"
] | 1,001 | 648 | 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,384 |
d4f4d6341f52cceb862faa89e85a42a3 | Given a positive integer n. Find three distinct positive integers a, b, c such that a + b + c = n and \operatorname{gcd}(a, b) = c, where \operatorname{gcd}(x, y) denotes the greatest common divisor (GCD) of integers x and y. | ['brute force', 'constructive algorithms', 'math', 'number theory'] | import math
case = int(input())
i=1
while i <= case:
i=i+1
n = int(input())
j=1
while (n-1)%j ==0:
j=j+1
else:
if j==2:
print(math.floor(n/2),math.floor(n/2)-1,1)
else:
k = 2
while math.gcd(k, n - 1) != 1:
k = k + 1
else:
print(k, n - k - 1, 1)
| Python | [
"math",
"number theory"
] | 279 | 399 | 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
} | 47 |
ff0d972460443cc13156ede0d4a16f52 | During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out. | ['dp', 'strings'] | import sys
range = xrange
input = raw_input
def partial(s):
g, pi = 0, [0] * len(s)
for i in range(1, len(s)):
while g and (s[g] != s[i]):
g = pi[g - 1]
pi[i] = g = g + (s[g] == s[i])
return pi
A = input()
B = input()
C = input()
A = [ord(c) - 97 if c != '*' else -1 for c in A]
B = [ord(c) - 97 for c in B]
C = [ord(c) - 97 for c in C]
n = len(A)
BB = partial(B)
CC = partial(C)
m = len(B)
k = len(C)
inf = 10**9
DP = [[[-inf]*(k + 1) for i in range(m + 1)] for i in range(n + 1)]
DP[0][0][0] = 0
for i in range(1, n + 1):
DPi = DP[i]
DPim1 = DP[i - 1]
for c in (range(0, 26) if A[i - 1] < 0 else (A[i - 1],)):
for a in range(m + 1):
newa = a
if newa == m:
newa = BB[newa - 1]
while newa and B[newa] != c:
newa = BB[newa - 1]
newa += B[newa] == c
DPinewa = DPi[newa]
DPim1a = DPim1[a]
for b in range(k + 1):
newb = b
if newb == k:
newb = CC[newb - 1]
while newb and C[newb] != c:
newb = CC[newb - 1]
newb += C[newb] == c
DPinewa[newb] = max(DPinewa[newb], DPim1a[b] + (newa == m) - (newb == k))
print max([max(d) for d in DP[n]]) | Python | [
"strings"
] | 1,124 | 1,363 | 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,827 |
968b3db21bd16bc04bdb355e98079d5d | You are given a tree that consists of n nodes. You should label each of its n-1 edges with an integer in such way that satisfies the following conditions: each integer must be greater than 0; the product of all n-1 numbers should be equal to k; the number of 1-s among all n-1 integers must be minimum possible. Let's define f(u,v) as the sum of the numbers on the simple path from node u to node v. Also, let \sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j) be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo 10^9 + 7.In this problem, since the number k can be large, the result of the prime factorization of k is given instead. | ['dp', 'greedy', 'number theory', 'math', 'implementation', 'sortings', 'dfs and similar', 'trees'] | import sys
def input():
return sys.stdin.readline()[:-1]
mod = 10**9 + 7
def main():
t = int(input())
for i in range(t):
n = int(input())
e_list = [[] for i in range(n)]
for j in range(n-1):
a,b = list(map(int,input().split()))
a,b = a-1,b-1
e_list[a].append(b)
e_list[b].append(a)
m = int(input())
p = list(map(int,input().split()))
from collections import deque
vi = 0 #change
INF = float('inf')
Q = deque([vi])
checked_list = [False]*n
checked_list[vi]=True
parent_list = [-1]*n
min_path_list = [INF]*n #change
min_path_list[vi] = 0
while len(Q)>0:
v = Q.pop()
for v1 in e_list[v]:
if not checked_list[v1]:
checked_list[v1]=True
Q.appendleft(v1)
parent_list[v1] = v
min_path_list[v1] = min_path_list[v]+1
memo = [-1]*n
min_path = [(i,min_path_list[i]) for i in range(n)]
min_path.sort(key=lambda x:x[1],reverse=True)
for v,d in min_path:
if v==0:
continue
count = 0
for v1 in e_list[v]:
if v1!=parent_list[v]:
#print(v1)
count+=memo[v1]+1
memo[v] = count
#print(memo)
#print(e_list)
memo = [(memo[i]+1)*(n-memo[i]-1) for i in range(1,n)]
memo.sort(reverse=True)
p.sort(reverse=True)
#print(memo)
ans = 0
if m<=n-1:
for i in range(m):
ans+=p[i]*memo[i]
ans%=mod
for i in range(m,n-1):
ans+=memo[i]
ans%=mod
else:
a = 1
for i in range(m-n+2):
a*=p[i]
a%=mod
ans = a*memo[0]
ans%=mod
for i in range(1,n-1):
ans+=p[i+m-n+1]*memo[i]
ans%=mod
print(ans)
if __name__ == '__main__':
main()
| Python | [
"graphs",
"math",
"number theory",
"trees"
] | 811 | 2,209 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 1,119 |
915bb1dec7af4427c4cc33f7803f6651 | Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant. | ['constructive algorithms', 'dfs and similar', 'trees'] | from math import *
from Queue import *
nMax = 310
def bfs(a,b):
par = [0 for i in range(nMax)]
marked = [b]
Q = [b]
while len(Q) > 0:
v = Q.pop()
for n in nbr[v]:
if n not in marked:
marked.append(n)
Q.append(n)
par[n] = v
v = a
l = []
while par[v] > 0:
l.append(v)
v = par[v]
l.append(v)
return l
n = int(raw_input())
nbr = [[] for i in range(n+1)]
for i in range(n-1):
l = map(int, raw_input().split())
nbr[l[0]].append(l[1])
nbr[l[1]].append(l[0])
l = map(int, raw_input().split())
ver = [1] + l + [1]
path = []
for i in range(len(ver)-1):
path += bfs(ver[i], ver[i+1])[:-1]
path += [1]
if len(path) == 2*n-1:
s = ''
for p in path:
s += str(p) + ' '
print(s[:-1])
else:
print(-1)
| Python | [
"graphs",
"trees"
] | 621 | 856 | 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,045 |
8f02891aa9d2fcd1963df3a4028aa5c0 | Alice and Bob are playing a game with strings. There will be t rounds in the game. In each round, there will be a string s consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from s.More formally, if there was a string s = s_1s_2 \ldots s_k the player can choose a substring s_ls_{l+1} \ldots s_{r-1}s_r with length of corresponding parity and remove it. After that the string will become s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of \texttt{a} is 1, the value of \texttt{b} is 2, the value of \texttt{c} is 3, \ldots, and the value of \texttt{z} is 26. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible. | ['games', 'greedy', 'strings'] | for test_c in range(int(input())):
word = input()
word_2_num=[ord(i)-96 for i in word]
if len(word_2_num)==1:
print("Bob",word_2_num[0])
elif len(word_2_num)%2==0:
print("Alice",sum(word_2_num))
else:
print("Alice",sum(word_2_num)-2*min(word_2_num[0],word_2_num[-1])) | Python | [
"strings",
"games"
] | 1,264 | 319 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 2,439 |
21672f2906f4f821611ab1b6dfc7f081 | Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.Suppose Ciel and Jiro play optimally, what is the score of the game? | ['greedy', 'sortings', 'games'] | n = input()
cie = jir = 0
mid = []
for i in xrange(n):
card = map(int, raw_input().split())
s = card[0]
card = card[1:]
b = s / 2
e = (s + 1) / 2
if(b != e):
mid.append(card[b])
cie += sum(card[:b])
jir += sum(card[e:])
l = (len(mid) + 1) / 2
mid = sorted(mid, reverse = True)
for i in xrange(len(mid)):
if(i % 2 == 0):
cie += mid[i]
else:
jir += mid[i]
print cie,jir
| Python | [
"games"
] | 516 | 385 | 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,518 |
dd26f45869b73137e5e5cc6820cdc2e4 | Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol. | ['implementation', 'brute force', 'strings'] | n, m = map(int, raw_input().split())
s = raw_input()
t = raw_input()
ans = float('inf')
pos = []
for i in xrange(m-n+1):
count = 0
tempPos = []
for j in xrange(n):
if t[i+j] != s[j]:
count += 1
tempPos.append(j+1)
if count < ans:
ans = count
pos = tempPos
print ans
for i in pos:
print i, | Python | [
"strings"
] | 1,114 | 368 | 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,764 |
8f00837e04627e445dfb8b6cd0216640 | Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 \rightarrow 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it. | ['greedy', 'math', 'strings'] | t =int(input())
while t!=0:
t-=1
n=int(input())
s=input()
ar=[]
sar=[]
for i in s:
if i!='0':
ar.append(int(i))
sar.append(i)
if len(ar)==0 or len(ar)==1 :
print(-1)
continue
else:
tsum=sum(ar)
if tsum%2==0 and ar[len(ar)-1]%2!=0:
print("".join(sar))
elif tsum%2==0 and (ar[len(ar)-1]%2)==0:
# print(1)
while len(ar)>0 and (ar[len(ar)-1])%2==0:
#print(ar[len(ar)-1])
ar.pop()
sar.pop()
if(len(ar)==0):
print(-1)
continue
print("".join(sar))
continue
elif tsum%2!=0 and (ar[len(ar)-1]%2)==0:
for i in ar:
if(i%2==1):
ar.remove(i)
sar.remove(str(i))
break
while len(ar)>0 and (ar[len(ar)-1])%2==0:
ar.pop()
sar.pop()
if(len(ar)==0):
print(-1)
continue
print("".join(sar))
continue
elif tsum%2!=0 and (ar[len(ar)-1]%2)!=0:
if(sum(ar)%2!=0):
for i in ar:
if(i%2==1):
ar.remove(i)
sar.remove(str(i))
break
if(ar[len(ar)-1]%2==0):
print(-1)
continue
print("".join(sar))
continue
else:
print(-1)
| Python | [
"math",
"strings"
] | 1,305 | 1,588 | 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,821 |
833e5aaee828fa2db3882e46bea1a0df | You are given n strings s_1, s_2, \ldots, s_n, each consisting of lowercase and uppercase English letters. In addition, it's guaranteed that each character occurs in each string at most twice. Find the longest common subsequence of these strings.A string t is a subsequence of a string s if t can be obtained from s by deletion of several (possibly, zero or all) symbols. | ['bitmasks', 'dp', 'graphs', 'strings'] | ''' F. Strange LCS
https://codeforces.com/contest/1589/problem/F
'''
import io, os, sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str
output = sys.stdout.write
def atoi(c):
if 'a' <= c <= 'z': return ord(c) - ord('a')
return ord(c) - ord('A') + 26
def itoa(i):
if i >= 26: return chr(i + ord('A') - 26)
return chr(i + ord('a'))
# see also CF 463D
# https://codeforces.com/contest/1588/submission/135825460
# find longest path in DAG where
# * node (c, mask) = V
# * char c appears in all strs
# * mask[i] = c appears in strs[i] as 1st/2nd occurrence
# * V = Nd vector, V[i] = index (c, mask) in strs[i]
# * edge (c1, mask1)=V1 -> (c2, mask2)=V2
# * if V[i] < V2[i], i.e. (c1, mask) appears before (c2, mask) in all strs
def solve(N, strs):
# cnt[c] = num strs containing char c
cnt = [0]*52
# pos[c][i][b] = idx of b-th occurrence of char c in strs[i]
pos = [[[-1]*2 for _ in range(N)] for _ in range(52)]
for i, s in enumerate(strs):
for j, c in enumerate(s):
c = atoi(c)
if pos[c][i][0] == -1:
pos[c][i][0] = j
cnt[c] += 1
else:
pos[c][i][1] = j
# longest path from node (c, mask)
def dfs(c, mask, memo):
if (c, mask) in memo: return memo[c, mask]
res = ''
for nc in range(52):
if cnt[nc] < N: continue
nmask = 0 # min valid pos of nc
valid = True # whether can move to (nc, nmask)
for i in range(N):
# cur pos of c < 1st pos of nc -> use 1st pos
if pos[c][i][(mask>>i) & 1] < pos[nc][i][0]: continue
# cur pos of c < 2nd pos of nc -> use 2nd pos
if pos[c][i][(mask>>i) & 1] < pos[nc][i][1]:
nmask |= 1 << i
continue
# cur pos of c > 2nd pos of nc -> invalid
valid = False
break
if valid:
cand = dfs(nc, nmask, memo)
if len(res) < len(cand): res = cand
memo[c, mask] = itoa(c) + res
return memo[c, mask]
# try starting path from each char, 1st occurrence (mask=0)
res = ''
memo = {}
for c in range(52):
if cnt[c] < N: continue
cand = dfs(c, 0, memo)
if len(res) < len(cand): res = cand
return res
def main():
T = int(input())
for _ in range(T):
N = int(input())
strs = [input().decode().strip() for _ in range(N)]
out = solve(N, strs)
print(len(out))
print(out)
if __name__ == '__main__':
main()
| Python | [
"graphs",
"strings"
] | 407 | 2,306 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 218 |
bdd1974e46f99eff3d03ed4174158dd9 | Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given n positive integers a_1, a_2, \dots, a_n. Using each of them exactly at once, you're to make such sequence b_1, b_2, \dots, b_n that sequence c_1, c_2, \dots, c_n is lexicographically maximal, where c_i=GCD(b_1,\dots,b_i) - the greatest common divisor of the first i elements of b. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence a is lexicographically smaller than a sequence 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 sequence a has a smaller element than the corresponding element in b. | ['number theory', 'greedy', 'math', 'brute force'] | import math
def get_int():
return int(input())
def get_int_list():
return list(map(int, input().split()))
def get_char_list():
return list(input())
def gcd(x, y):
if x < y:
return gcd(y, x)
z = x % y
if z == 0:
return y
else:
return gcd(y, z)
cases = get_int()
for _ in range(cases):
n = get_int()
ints = get_int_list()
v = max(ints)
result = [v]
visited = set()
visited.add(ints.index(v))
while len(visited) < n:
md = 0
t = None
for i, d in enumerate(ints):
if i in visited:
continue
cd = gcd(v, d)
if cd > md:
md = cd
t = i
v = md
result.append(ints[t])
visited.add(t)
print(*result) | Python | [
"math",
"number theory"
] | 1,211 | 817 | 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,682 |
cff3074a82bffdd49579a47c7491f972 | It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has gi Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation f of {1, 2, ..., m}, such that f(x) = y means that a Pokemon of type x evolves into a Pokemon of type y.The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol.Two evolution plans f1 and f2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f1(i) ≠ f2(i).Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109 + 7. | ['data structures', 'sortings', 'hashing', 'strings'] | # ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict,Counter
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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------------------------------------
for ik in range(1):
n,m=map(int,input().split())
#s = Factorial(mod)
d=defaultdict(list)
for i in range(n):
l=list(map(int,input().split()))
for j in range(1,l[0]+1):
d[l[j]].append(i)
w=m-len(d)
ans=1
#x=list(map(str,d.values()))
tot=defaultdict(int)
#print(x)
for i in d:
str1 = ""
for ele in d[i]:
str1 += str(ele)+" "
#print(str1,end=' ')
tot[str1]+=1
#print()
for e1 in tot:
e=tot[e1]
for i in range(2, e + 1):
ans = ans * i % mod
for i in range(2, w + 1):
ans = ans * i % mod
print(ans)
| Python | [
"strings"
] | 1,773 | 17,207 | 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,026 |
b9f0c38c6066bdafa2e4c6daf7f46816 | You are given a string s consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer t independent queries. | ['constructive algorithms', 'sortings', 'greedy', 'strings'] | for i in range(int(input())):
k=input()
if len(set(k))==1:
print("-1")
continue
else:
r = ''.join(sorted(k))
print(str(r)) | Python | [
"strings"
] | 537 | 133 | 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,935 |
0369c070f4ac9aba4887bae32ad8b85b | Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are n cities and n−1 undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from 1 to n and the city 1 is a capital. In other words, the country has a tree structure.There are m citizens living in the country. A p_i people live in the i-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the i-th city calculates a happiness index h_i as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city i the happiness index will be equal exactly to h_i". | ['greedy', 'dfs and similar', 'trees', 'math'] | import os
import sys
from io import BytesIO, IOBase
import math
def dfsVisited (G, node, nodeInfo, V, P):
V.add (node)
ans = 0
for v in G[node]:
if v not in V:
ans += dfsVisited (G, v, nodeInfo, V, P)
ans += P[node-1]
nodeInfo[node-1][0] = ans
return ans
def dfsCheckBecameHappy (G, node, nodeInfo, V):
V.add (node)
childUnhappy = 0
childHappy = 0
for v in G[node]:
if v not in V:
childHappy += nodeInfo[v-1][1]
if childHappy > nodeInfo[node-1][1]: return False
ans = True
for v in G[node]:
if v not in V:
ans = ans and dfsCheckBecameHappy (G, v, nodeInfo, V)
return ans
def main():
t = int(input())
for _ in range (t):
n,m = map(int, input().split())
P = list(map(int, input().split()))
H = list(map(int, input().split()))
root = 1
graph = dict()
nodeInfo = [[-1]*3 for i in range (n)] #visitedPeople, happy, unhappy
for i in range (1, n+1):
graph[i] = list()
for _ in range (n-1):
u,v = map(int, input().split())
graph[u].append (v)
graph[v].append (u)
visited = set()
_ = dfsVisited(graph, 1, nodeInfo, visited, P)
okay = True
for i in range (n):
happy = (nodeInfo[i][0]+H[i])/2
if math.floor(happy) != math.ceil(happy):
okay = not okay
break
unhappy = nodeInfo[i][0]-happy
if happy<0 or unhappy<0:
okay = not okay
break
nodeInfo[i][1] = int(happy)
nodeInfo[i][2] = int(unhappy)
if not okay:
print ("NO")
continue
visited = set()
if dfsCheckBecameHappy (graph, 1, nodeInfo, visited):
print ("YES")
else:
print ("NO")
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = lambda s: self.buffer.write(s.encode()) if self.writable else None
def read(self):
if self.buffer.tell():
return self.buffer.read().decode("ascii")
return os.read(self._fd, os.fstat(self._fd).st_size).decode("ascii")
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().decode("ascii")
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
def print(*args, sep=" ", end="\n", file=sys.stdout, flush=False):
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(end)
if flush:
file.flush()
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
sys.setrecursionlimit(int(1e7))
if __name__ == "__main__":
main() | Python | [
"graphs",
"math",
"trees"
] | 1,775 | 3,528 | 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
} | 108 |
2df45858a638a90d30315844df6d1084 | Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (x1, y1) and (x2, y2).Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the i-th mouse is equal to (vix, viy), that means that the x coordinate of the mouse increases by vix units per second, while the y coordinates increases by viy units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap.Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once. | ['geometry', 'implementation', 'sortings', 'math'] | rd = lambda: map(int, input().split())
n = int(input())
x1, y1, x2, y2 = rd()
l = []
r = []
m = []
for i in range(n):
t = []
rx, ry, vx, vy = rd()
m.append([rx, ry, vx, vy])
if x1 <= rx <= x2 and y1 <= ry <= y2:
t.append(0)
if vx == 0 and vy == 0:
t.append(0x3f3f3f3f3f3f3f3f)
if vx:
t1 = (x1 - rx) / vx
if t1 >= 0:
if y1 <= ry + t1 * vy <= y2:
t.append(t1)
t1 = (x2 - rx) / vx
if t1 >= 0:
if y1 <= ry + t1 * vy <= y2:
t.append(t1)
if vy:
t1 = (y1 - ry) / vy
if t1 >= 0:
if x1 <= rx + t1 * vx <= x2:
t.append(t1)
t1 = (y2 - ry) / vy
if t1 >= 0:
if x1 <= rx + t1 * vx <= x2:
t.append(t1)
if len(t) < 2:
print(-1)
exit()
t.sort()
l.append(t[0])
r.append(t[-1])
l.sort()
r.sort()
if l[-1] > r[0]:
print(-1)
else:
p = (l[-1] + r[0]) / 2
if not all(x1 < rx + p * vx < x2 and y1 < ry + p * vy < y2 for rx, ry, vx, vy in m):
print(-1)
else:
print(l[-1])
| Python | [
"math",
"geometry"
] | 1,183 | 1,139 | 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,186 |
9c84eb518c273942650c7262e5d8b45f | Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border). | ['geometry'] | #------------------------------what is this I don't know....just makes my mess faster--------------------------------------
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")
#----------------------------------Real game starts here--------------------------------------
'''
___________________THIS IS AESTROIX CODE________________________
KARMANYA GUPTA
'''
n , d = list(map(int, input().split()))
for i in range(int(input())):
x , y = list(map(int, input().split()))
a = y-x
b = y+x
if a < d and a > -d and b > d and b < 2*n - d:
print("YES")
elif a == d or a == -d or b == d or b == 2*n - d:
print("YES")
else:
print("NO")
| Python | [
"geometry"
] | 707 | 2,373 | 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
} | 61 |
bc5fb5d6882b86d83e5c86f21d806a52 | Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.He wants to distribute all these n coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives A coins to Alice, B coins to Barbara and C coins to Cerene (A+B+C=n), then a + A = b + B = c + C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all n coins between sisters in a way described above.You have to answer t independent test cases. | ['math'] | t = int(input())
for _ in range(t):
a,b,c,n = map(int, input().split())
m = max(a,b,c)
for i in [a,b,c]:
p = m-i
i+=p
n-=p
if n%3==0 and n>=0:
print("YES")
else:
print("NO")
| Python | [
"math"
] | 908 | 189 | 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,248 |
92c2f3599d221f2b1b695227c5739e84 | It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer — as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored.Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal).The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall. In the given coordinate system you are given: y1, y2 — the y-coordinates of the side pillars of the goalposts of robo-Wallace's opponents; yw — the y-coordinate of the wall to which Robo-Wallace is aiming; xb, yb — the coordinates of the ball's position when it is hit; r — the radius of the ball. A goal is scored when the center of the ball crosses the OY axis in the given coordinate system between (0, y1) and (0, y2). The ball moves along a straight line. The ball's hit on the wall is perfectly elastic (the ball does not shrink from the hit), the angle of incidence equals the angle of reflection. If the ball bounces off the wall not to the goal, that is, if it hits the other wall or the goal post, then the opposing team catches the ball and Robo-Wallace starts looking for miscalculation and gets dysfunctional. Such an outcome, if possible, should be avoided. We assume that the ball touches an object, if the distance from the center of the ball to the object is no greater than the ball radius r. | ['geometry'] | from math import atan, asin
y1, y2, yw, xb, yb, r = map(float, input().split())
x = xb * (yw - y1 - 2*r) / (2*yw - y1 - yb - 3*r)
alpha = atan(x / (yw - y1 - 2*r))
beta = asin(r / (y2 - y1 - r))
print ('-1' if alpha < beta else '{0:.10f}'.format(x)) | Python | [
"geometry"
] | 2,923 | 249 | 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,780 |
8b926a19f380a56018308668c17c6928 | Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were n types of candies, there are a_i candies of the type i (1 \le i \le n).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row. | ['math'] | for t in range(int(input())):
n = input()
candies = sorted(list(map(int, input().split())))
if len(candies) == 1:
res = 'Yes' if candies[0] == 1 else 'No'
else:
res = 'Yes' if candies[-1] - candies[-2] <= 1 else 'No'
print(res) | Python | [
"math"
] | 586 | 252 | 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,137 |
e3ec343143419592e73d4be13bcf1cb5 | Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.Mr. Kitayuta wants you to process the following q queries.In the i-th query, he gives you two integers — ui and vi.Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. | ['dp', 'dsu', 'dfs and similar', 'graphs'] | n, m = map(int, raw_input().split(' '))
mp = [[set() for j in range(0, n)] for i in range(0, n)]
for i in range(0, m):
a, b, c = map(int, raw_input().split(' '))
a -= 1
b -= 1
if c not in mp[a][b]:
mp[a][b].add(c)
mp[b][a].add(c)
# print mp
for k in range(0, n):
for i in range(0, n):
for j in range(0, n):
mp[i][j] |= (mp[i][k]&mp[k][j])
# print mp
q = int(raw_input())
for i in range(0, q):
u, v = map(int, raw_input().split(' '))
u -= 1
v -= 1
print len(mp[u][v]) if mp[u][v] else 0 | Python | [
"graphs"
] | 471 | 557 | 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,265 |
9c90974a0bb860a5e180760042fd5045 | An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there. | ['implementation', 'strings'] | n, m = list(map(int, input().strip().split()))
A = [[0] * m] * n
for r in range(n):
A[r] = list(input().strip())
def in_row(A, r, c):
x = A[r][c]
left, right = A[r][:c], A[r][c + 1:]
if (x in left) or (x in right):
return True
def in_col(A, r, c):
x = A[r][c]
for row in range(n):
if row == r:
continue
if A[row][c] == x:
return True
out = ''
for r in range(n):
for c in range(m):
if not in_row(A, r, c) and not in_col(A, r, c):
out += A[r][c]
print(out) | Python | [
"strings"
] | 919 | 559 | 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,470 |
37bef742c08e1969b609e39fd6eb8f69 | One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal s towards a faraway galaxy. Recently they've received a response t which they believe to be a response from aliens! The scientists now want to check if the signal t is similar to s.The original signal s was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal t, however, does not look as easy as s, but the scientists don't give up! They represented t as a sequence of English letters and say that t is similar to s if you can replace all zeros in s with some string r_0 and all ones in s with some other string r_1 and obtain t. The strings r_0 and r_1 must be different and non-empty.Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings r_0 and r_1) that transform s to t. | ['data structures', 'hashing', 'brute force', 'strings'] | s = input()
t = input()
n,m = len(s), len(t)
a = s.count('0')
b = len(s) - a
pow = [1] * m
h = [0] * (m+1)
p, mod = 31, 10**9+9
for i in range(1, m):
pow[i] = pow[i-1] * p % mod
for i in range(m):
h[i+1] = (h[i] + (ord(t[i])-ord('a')+1) * pow[i]) % mod
def get_hash(i, j):
hash_value = (h[j] - h[i] + mod) % mod
hash_value = (hash_value * pow[m-i-1]) % mod
return hash_value
def check(x, y):
index = 0
hash_x = hash_y = -1
for i in range(n):
if s[i] == '0':
if hash_x == -1:
hash_x = get_hash(index, index+x)
else:
if get_hash(index, index+x) != hash_x: return False
index += x
else:
if hash_y == -1:
hash_y = get_hash(index, index+y)
else:
if get_hash(index, index+y) != hash_y: return False
index += y
return hash_x != hash_y
res = 0
for x in range(1, m//a+1):
if (m - a*x) % b == 0:
y = (m - a*x) // b
if y == 0: continue
if check(x ,y):
res += 1
print(res) | Python | [
"strings"
] | 1,040 | 1,099 | 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,606 |
9dc500c1f7fe621351c1d5359e71fda4 | Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.There are n ghosts in the universe, they move in the OXY plane, each one of them has its own velocity that does not change in time: \overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j} where V_{x} is its speed on the x-axis and V_{y} is on the y-axis.A ghost i has experience value EX_i, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind GX = \sum_{i=1}^{n} EX_i will never increase.Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time T, and magically all the ghosts were aligned on a line of the form y = a \cdot x + b. You have to compute what will be the experience index of the ghost kind GX in the indefinite future, this is your task for today.Note that when Tameem took the picture, GX may already be greater than 0, because many ghosts may have scared one another at any moment between [-\infty, T]. | ['geometry', 'math'] | import sys
input = sys.stdin.readline
N,A,B = map(int,input().split())
POS = {}
for _ in range(N):
x,vx,vy = map(int,input().split())
v = (vx,vy)
score = vy - A*vx
if score not in POS:
POS[score] = {}
if v not in POS[score]:
POS[score][v] = 0
POS[score][v] += 1
COL = 0
for x in POS:
size = sum([POS[x][v] for v in POS[x]])
COL += size*(size-1)//2 - sum([max(0,POS[x][v]*(POS[x][v]-1)//2) for v in POS[x]])
COL *= 2
print(COL) | Python | [
"math",
"geometry"
] | 1,334 | 442 | 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,615 |
f5bcde6e3008405f61cead4e3f44806e | Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. | ['data structures', 'two pointers', 'number theory', 'brute force'] | ncases = int(input())
for i in range(ncases):
line1 = input().split(' ')
line2 = input().split(' ')
hate = int(line1[1])
arr = []
count = 0
for ele in line2:
ele = int(ele)
if (ele%hate == 0):
count += 1
arr.append(ele)
if (count == len(arr)):
print(-1)
elif (sum(arr)% hate != 0):
print (len(arr))
else:
s = []
for j in range(len(arr)):
find = arr[j]
if (find%hate!= 0):
s.append(j)
break
for k in range(-1,-(len(arr)+1),-1):
find = arr[k]
if (find%hate != 0):
s.append(k)
break
arr1 = arr[s[0]+1:]
arr2 = arr[0:s[1]]
print (max(len(arr1),len(arr2))) | Python | [
"number theory"
] | 471 | 800 | 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,590 |
bb9f0e0431ef4db83190afd7b9ed4496 | You are given a simple undirected graph with n vertices and m edges. Edge i is colored in the color c_i, which is either 1, 2, or 3, or left uncolored (in this case, c_i = -1).You need to color all of the uncolored edges in such a way that for any three pairwise adjacent vertices 1 \leq a < b < c \leq n, the colors of the edges a \leftrightarrow b, b \leftrightarrow c, and a \leftrightarrow c are either pairwise different, or all equal. In case no such coloring exists, you need to determine that. | ['brute force', 'graphs', 'math', 'matrices'] | from itertools import combinations
from collections import defaultdict
import io, os, sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def F1(A, B, C, D):
AD = A ^ D
return (AD ^ B) | (A ^ C), AD & (B ^ C)
def F2(A, B, C, D):
AC = A ^ C
return AC | (B ^ D), (AC ^ D) & (B ^ C)
def flip_bit(a, i):
a[i // l] ^= (1 << (i % l))
def Gauss(a, b, n, m):
if n == 0: return 2, [0] * m
where = [-1] * m
row, col = 0, 0
while col < m and row < n:
t1, t2 = divmod(col, l)
for i in range(row, n):
if a[i][t1] >> t2 & 1 or b[i][t1] >> t2 & 1:
a[i], a[row] = a[row], a[i]
b[i], b[row] = b[row], b[i]
break
if not a[row][t1] >> t2 & 1 and not b[row][t1] >> t2 & 1:
col += 1
continue
where[col] = row
for i in range(n):
if i == row: continue
x1, x2 = a[i][t1] >> t2 & 1, b[i][t1] >> t2 & 1
y1, y2 = a[row][t1] >> t2 & 1, b[row][t1] >> t2 & 1
cc = ((x1 + x2) * (y1 + y2)) % 3
if cc == 0: continue
F = F1 if cc == 2 else F2
for k in range(t1, U): a[i][k], b[i][k] = F(a[i][k], b[i][k], a[row][k], b[row][k])
col, row = col + 1, row + 1
ans = [0] * m
t1, t2 = divmod(m, l)
for i in range(m):
W = where[i]
if W != -1:
t3, t4 = divmod(i, l)
x1, x2 = a[W][t1] >> t2 & 1, b[W][t1] >> t2 & 1
y1, y2 = a[W][t3] >> t4 & 1, b[W][t3] >> t4 & 1
ans[i] = ((x1 + x2) * (y1 + y2)) % 3
for i in range(n):
sm = 0
for j in range(m):
t3, t4 = divmod(j, l)
sm += ((a[i][t3] >> t4 & 1) + (b[i][t3] >> t4 & 1)) * ans[j]
if (sm - (a[i][t1] >> t2 & 1) - (b[i][t1] >> t2 & 1)) % 3 != 0: return 0, [-1] * m
if -1 in where: return 2, ans
return 1, ans
T = int(input())
for _ in range(T):
n, m = [int(i) for i in input().split()]
l, U = 63, m//63 + 1
G = defaultdict(list)
edges_back = {}
colors = [0] * m
for k in range(m):
a, b, c = [int(i) for i in input().split()]
G[a] += [(b, c)]
G[b] += [(a, c)]
edges_back[(a, b)] = (k, c)
edges_back[(b, a)] = (k, c)
colors[k] = c
ans = set()
for n1 in range(1, n + 1):
neibs = G[n1]
for (n2, c12), (n3, c13) in combinations(neibs, 2):
if (n2, n3) in edges_back:
row = [[0] * U, [0] * U]
k12, _ = edges_back[(n1, n2)]
k13, _ = edges_back[(n1, n3)]
k23, c23 = edges_back[(n2, n3)]
last = 0
for k, c in (k12, c12), (k13, c13), (k23, c23):
if c != -1:
last -= c
else:
flip_bit(row[0], k)
last %= 3
if last == 1:
flip_bit(row[0], m)
elif last == 2:
flip_bit(row[0], m)
flip_bit(row[1], m)
ans.add(tuple(tuple(x) for x in row))
mat1, mat2 = [], []
for x, y in ans:
mat1 += [list(x)]
mat2 += [list(y)]
ans = Gauss(mat1, mat2, len(mat1), m)
if ans[0] == 0:
out = [-1]
else:
out = []
for i in range(m):
if colors[i] != -1:
out += [colors[i]]
elif ans[1][i] == 0:
out += [3]
else:
out += [ans[1][i]]
print(" ".join(str(x) for x in out))
| Python | [
"graphs",
"math"
] | 579 | 3,746 | 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
} | 755 |
deed251d324f7bbe53eefa94f92c3bbc | Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the i-th integer represents the color of the i-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than k, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing k to the right. To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array. | ['greedy', 'games'] | n, k = map(int, input().split())
P = map(int, input().split())
parent = list(range(256))
sz = [1] * 256
def rt(x):
if x != parent[x]:
parent[x] = rt(parent[x])
return parent[x]
def u(rx, ry):
parent[ry] = rx
sz[rx] += sz[ry]
ans = [0] * n
for i, p in enumerate(P):
rx = rt(p)
while rx > 0 and sz[rx] + sz[rt(rx - 1)] <= k:
u(rt(rx - 1), rx)
rx = rt(p)
ans[i] = rt(p)
print(' '.join(map(str, ans)))
| Python | [
"games"
] | 1,196 | 461 | 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
} | 3,408 |
0d95c84e73aa9b6567eadeb16acfda41 | You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.How many nice edges are there in the given tree? | ['dfs and similar', 'trees'] | #!/usr/bin/env python2
"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>
"""
from __future__ import division, print_function
import itertools
import os
import sys
from atexit import register
from io import BytesIO
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
res = 0
def main():
n = int(input())
a = input().split()
red_cnt = a.count('1')
blue_cnt = a.count('2')
tree = [[] for _ in range(n)]
for _ in range(n - 1):
v, u = map(int, input().split())
tree[v - 1].append(u - 1)
tree[u - 1].append(v - 1)
dp, visited = [[0, 0] for _ in range(n)], [False] * n
def dfs(node):
global res
finished = [False] * n
stack = [node]
while stack:
node = stack[-1]
node_cnt = dp[node]
if not visited[node]:
visited[node] = True
else:
stack.pop()
node_cnt[0] += a[node] == '1'
node_cnt[1] += a[node] == '2'
finished[node] = True
for child in tree[node]:
if not visited[child]:
stack.append(child)
elif finished[child]:
child_cnt = dp[child]
node_cnt[0] += child_cnt[0]
node_cnt[1] += child_cnt[1]
if ((child_cnt[0] == red_cnt) and (child_cnt[1] == 0)) or ((child_cnt[0] == 0) and
(child_cnt[1] == blue_cnt)):
res += 1
dfs(0)
print(res)
if __name__ == '__main__':
main()
| Python | [
"graphs",
"trees"
] | 476 | 1,939 | 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
} | 409 |
c2b3b577c2bcb3a2a8cb48700c637270 | There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms. | ['dp', 'combinatorics', 'probabilities'] | n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
prob = [(n+1)*[None] for _ in range(m+1)]
for k in range(1, m+1):
prob[k][0] = [1.0]
for i in range(1, n+1):
prob[k][i] = (i+1)*[0.0]
for j in range(i):
prob[k][i][j+1] += prob[k][i-1][j]*(1.0/k)
prob[k][i][j] += prob[k][i-1][j]*(1-1.0/k)
dp = [[(n+1)*[0.0] for _ in range(n+1)] for _ in range(m+1)]
dp[m][n][0] = 1.0
for k in range(m, 0, -1):
for i in range(n+1):
for x in range(n+1):
t = dp[k][i][x]
if t == 0.0:
continue
for j in range(i+1):
dp[k-1][i-j][max(x, (j+a[m-k]-1)/a[m-k])] += t*prob[k][i][j]
res = 0
for x in range(n+1):
res += x*dp[0][0][x]
print "%.13f" % res
| Python | [
"math",
"probabilities"
] | 534 | 783 | 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
} | 2,731 |
8639d3ec61f25457c24c5e030b15516e | You are given n integers a_1, a_2, \dots, a_n.For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. | ['constructive algorithms', 'number theory', 'math'] |
n=int(input())
l=list(map(int, input().split(' ')))
k1, k2=[],[]
def smallPrimes(num=10000007):
#prepare smallest prime factor array
smallestPrimes = [0]*(num+1)
#smallestPrimes[2] = 2
p=2
while(p<num+1):
if(smallestPrimes[p]==0):
for j in range(p, num+1,p):
if(smallestPrimes[j]==0):
smallestPrimes[j]=p
p+=1
return smallestPrimes
def getFactors(num):
factors=set()
global smallestPrimes;
while(num>1):
sp=smallestPrimes[num]
factors.add(sp)
num//=sp
return factors
def products(ll):
p=1
for j in ll[1:]:
p*=j
return p
smallestPrimes = smallPrimes()
for kk in l:
if(kk==1):
k1+=[-1]
k2+=[-1]
else:
factorList = list(getFactors(kk))
if(len(factorList)==1):
k1+=[-1]
k2+=[-1]
else:
k1+=[factorList[0]]
k2+=[products(factorList)]
for a in k1:
print(a, end=' ')
print()
for a in k2:
print(a, end=' ')
| Python | [
"number theory",
"math"
] | 291 | 889 | 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,439 |
ee32db0f67954ed0eccae1429819f4d7 | You are given n segments on the coordinate axis. The i-th segment is [l_i, r_i]. Let's denote the set of all integer points belonging to the i-th segment as S_i.Let A \cup B be the union of two sets A and B, A \cap B be the intersection of two sets A and B, and A \oplus B be the symmetric difference of A and B (a set which contains all elements of A and all elements of B, except for the ones that belong to both sets).Let [\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}] be an array where each element is either \cup, \oplus, or \cap. Over all 3^{n-1} ways to choose this array, calculate the sum of the following values:|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|In this expression, |S| denotes the size of the set S. | ['data structures', 'dp', 'matrices', 'probabilities'] | import cProfile
import sys
import io
import os
import traceback
from collections import deque
from itertools import accumulate
# region IO
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = io.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(io.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()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip('\r\n')
def read_int_list():
return list(map(int, input().split()))
def read_int_tuple():
return tuple(map(int, input().split()))
def read_int():
return int(input())
# endregion
# region local test
if 'AW' in os.environ.get('COMPUTERNAME', ''):
test_no = 1
# f = open(os.path.dirname(__file__) + f'\\in{test_no}.txt', 'r')
f = open('inputs')
def input():
return f.readline().rstrip("\r\n")
# endregion
class SegmentTree():
__slots__ = ['n', 'oper', 'e', 'log', 'size', 'data']
def __init__(self, n, oper, e):
self.n = n
self.oper = oper
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.data = [list(e) for _ in range(2 * self.size)]
# def _update(self, k):
# self.oper(self.data[k], self.data[2 * k], self.data[2 * k + 1])
def build(self, arr):
# assert len(arr) <= self.n
for i in range(self.n):
t = self.data[self.size + i]
t[0], t[1], t[2], t[3] = arr[i]
for i in range(self.size - 1, 0, -1):
# self._update(i)
self.oper(self.data[i], self.data[2 * i], self.data[2 * i + 1])
def set(self, p, x):
# assert 0 <= p < self.n
p += self.size
# self.data[p] = x
t = self.data[p]
t[0], t[1], t[2], t[3] = x
for i in range(self.log):
p >>= 1
# self._update(p)
self.oper(self.data[p], self.data[2 * p], self.data[2 * p + 1])
MOD = 998244353 # 1000000007
N = 300000 + 32
pos = [[] for _ in range(N)]
ZERO = (3, 0, 1, 2) # [3, 0], [1, 2]
ONE = (1, 2, 1, 2) # [1, 2], [1, 2]
E = (1, 0, 0, 1) # [1, 0], [0, 1]
def OPER(tn, fn, gn):
tn[0] = (fn[0] * gn[0] % MOD + fn[1] * gn[2] % MOD) % MOD
tn[1] = (fn[0] * gn[1] % MOD + fn[1] * gn[3] % MOD) % MOD
tn[2] = (fn[2] * gn[0] % MOD + fn[3] * gn[2] % MOD) % MOD
tn[3] = (fn[2] * gn[1] % MOD + fn[3] * gn[3] % MOD) % MOD
n = read_int()
def main():
st = SegmentTree(n - 1, OPER, E)
st.build([ZERO for _ in range(n)])
book = [[] for _ in range(N)]
m = 0
for i in range(n):
l, r = read_int_tuple()
book[l].append((1, i))
book[r + 1].append((0, i))
if m < r + 1: m = r + 1
cur = res = 0
for i in range(m):
for c, j in book[i]:
if j == 0: cur = c
else: st.set(j - 1, ONE if c else ZERO)
res += st.data[1][cur * 2 + 1]
res %= MOD
print(res)
main()
# cProfile.run("main()")
# n = read_int()
#
# def main():
# def matmul(k, i, j):
# u1, u2, u3, u4 = tree1[i], tree2[i], tree3[i], tree4[i]
# v1, v2, v3, v4 = tree1[j], tree2[j], tree3[j], tree4[j]
# tree1[k] = (u1 * v1 % mod + u2 * v3 % mod) % mod
# tree2[k] = (u1 * v2 % mod + u2 * v4 % mod) % mod
# tree3[k] = (u3 * v1 % mod + u4 * v3 % mod) % mod
# tree4[k] = (u3 * v2 % mod + u4 * v4 % mod) % mod
# return
#
# def update(i, x):
# i += l1
# if x:
# tree1[i], tree2[i] = 2, 2
# tree3[i], tree4[i] = 1, 1
# else:
# tree1[i], tree2[i] = 2, 0
# tree3[i], tree4[i] = 1, 3
# i //= 2
# while i:
# matmul(i, 2 * i, 2 * i + 1)
# i //= 2
# return
#
# mod = 998244353
# m = 3 * pow(10, 5) + 5
# l1 = pow(2, n.bit_length())
# l2 = 2 * l1
# tree1, tree2 = [1] * l2, [0] * l2
# tree3, tree4 = [0] * l2, [1] * l2
# for i in range(l1, l1 + n - 1):
# tree1[i], tree2[i] = 2, 0
# tree3[i], tree4[i] = 1, 3
# for i in range(l1 - 1, 0, -1):
# matmul(i, 2 * i, 2 * i + 1)
# x = [[] for _ in range(m + 1)]
# for i in range(n):
# l, r = read_int_tuple()
# x[l].append(n - i - 1)
# x[r + 1].append(n - i - 1)
# now = [0] * n
# ans = 0
# for i in range(m + 1):
# for j in x[i]:
# now[j] ^= 1
# if j < n - 1:
# update(j, now[j])
# u1, u2 = tree1[1], tree2[1]
# if now[-1]:
# v1, v2 = 1, 0
# else:
# v1, v2 = 0, 1
# ans += u1 * v1 % mod + u2 * v2 % mod
# ans %= mod
# ans %= mod
# print(ans)
#
# cProfile.run("main()")
| Python | [
"math",
"probabilities"
] | 945 | 6,802 | 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
} | 188 |
6090c7745184ede5a9997dc0dff39ac2 | This is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are even.There are n fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.There are an infinite number of cows on the plane, one at every point with integer coordinates.Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting 3 distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting.Find the number of interesting fences. | ['bitmasks', 'geometry', 'math', 'number theory'] | import sys
input = sys.stdin.readline
n = int(input())
a = 0
b = 0
c = 0
d = 0
for i in range(n):
x, y = [int(xx) for xx in input().split()]
if x % 4 and y % 4:
a += 1
elif y % 4:
b += 1
elif x % 4:
c += 1
else:
d += 1
print(a * (a - 1) // 2 * (b + c + d) +
b * (b - 1) // 2 * (a + c + d) +
c * (c - 1) // 2 * (a + b + d) +
d * (d - 1) // 2 * (a + b + c) +
a * (a - 1) * (a - 2) // 6 +
b * (b - 1) * (b - 2) // 6 +
c * (c - 1) * (c - 2) // 6 +
d * (d - 1) * (d - 2) // 6)
| Python | [
"math",
"number theory",
"geometry"
] | 699 | 594 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,611 |
609c531258612e58c4911c650e90891c | Kuzya started going to school. He was given math homework in which he was given an array a of length n and an array of symbols b of length n, consisting of symbols '*' and '/'.Let's denote a path of calculations for a segment [l; r] (1 \le l \le r \le n) in the following way: Let x=1 initially. For every i from l to r we will consequently do the following: if b_i= '*', x=x*a_i, and if b_i= '/', then x=\frac{x}{a_i}. Let's call a path of calculations for the segment [l; r] a list of all x that we got during the calculations (the number of them is exactly r - l + 1). For example, let a=[7, 12, 3, 5, 4, 10, 9], b=[/, *, /, /, /, *, *], l=2, r=6, then the path of calculations for that segment is [12, 4, 0.8, 0.2, 2].Let's call a segment [l;r] simple if the path of calculations for it contains only integer numbers. Kuzya needs to find the number of simple segments [l;r] (1 \le l \le r \le n). Since he obviously has no time and no interest to do the calculations for each option, he asked you to write a program to get to find that number! | ['data structures', 'number theory'] | import sys,math
from collections import defaultdict
N = 1000005
maxf = [0] * N
for i in range(2,int(math.sqrt(N))+2):
if maxf[i] == 0:
for j in range(i+i, N, i):
maxf[j] = i
for i in range(2, N):
if maxf[i] == 0: maxf[i] = i
n = int(sys.stdin.readline())
a = [int(i) for i in sys.stdin.readline().split()]
p = defaultdict(list)
l = [0]*n
r = 0
for idx, i in enumerate(sys.stdin.readline().strip()):
x = a[idx]
l[idx] = idx+1
if i == '*':
while x > 1:
p[maxf[x]].append(idx+1)
x//=maxf[x]
else:
while x > 1:
l[idx] = min(l[idx], p[maxf[x]].pop()) if p[maxf[x]] else 0
x//=maxf[x]
st = []
for i in range(n):
st.append(i+1)
while st and st[-1] > l[i]: st.pop()
r+=len(st)
print(r)
| Python | [
"number theory"
] | 1,295 | 830 | 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
} | 149 |
19a3247ef9d10563db821ca19b0f9004 | This is the hard version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation: replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+".How many non-empty substrings of the given string s are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string s.Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++". | ['data structures', 'implementation', 'math', 'strings'] | import sys
def Print( m ):
for r in m:
print( r )
print()
def Solve( size, s ):
cntM = 0
delta = [ 0 ]
for idx in range( size ):
c = s[idx]
if c == '+':
cntM -= 1
else :
cntM += 1
delta.append( cntM )
minDelta = min( delta )
maxDelta = max( delta )
sol3 = 0
collecteds = { key : 0 for key in range( minDelta, maxDelta + 1) }
collecteds[0] = 1
sums1 = { key:0 for key in range( minDelta - 3, maxDelta + 1) }
sums1[ 0 ] = 1
for i in range( 1, size + 1 ):
k = delta[i]
#print( '\n'*2, k )
#print( 'col', collecteds )
#print( 'sum ', dict( sorted(sums.items() )) )
#print( 'sum1', dict( sorted(sums1.items())[3:] ) )
#print( 'sum[k] and sum1[k]', k, sums[k], sums1[k] )
sol3 += sums1[ k - 3 ] + collecteds[ k ]
collecteds[ k ] += 1
sums1[ k ] = sums1[ k - 3 ] + collecteds[ k ]
return sol3
def main():
input = sys.stdin
if len( sys.argv ) >= 2:
input = open( sys.argv[1], 'r' )
n = int( input.readline().strip() )
for i in range( n ):
input.readline()
s = input.readline().strip()
print( Solve( len( s ), s ) )
if __name__ == "__main__":
main()
| Python | [
"math",
"strings"
] | 1,259 | 1,397 | 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
} | 28 |
e7ffe7a54e2403805bde98d98fa0be3a | You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 and π. For example, opposite directions vectors have angle equals to π. | ['sortings', 'geometry'] | from math import atan2
s = lambda a, b: a[0] * b[0] + a[1] * b[1]
v = lambda a, b: a[0] * b[1] - a[1] * b[0]
p = []
for i in range(int(input())):
x, y = map(int, input().split())
p.append((atan2(x, y), (x, y), i + 1))
p.sort()
d = [(s(a, b), abs(v(a, b)), i, j) for (x, a, i), (y, b, j) in zip(p, p[1:] + p[:1])]
x = d[0]
for y in d:
if v(y[:2], x[:2]) > 0: x = y
print(x[2], x[3])
| Python | [
"geometry"
] | 389 | 399 | 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
} | 697 |
299c209b070e510e7ed3b525f51fec8a | You are given a complete bipartite graph with 2n nodes, with n nodes on each side of the bipartition. Nodes 1 through n are on one side of the bipartition, and nodes n+1 to 2n are on the other side. You are also given an n \times n matrix a describing the edge weights. a_{ij} denotes the weight of the edge between nodes i and j+n. Each edge has a distinct weight.Alice and Bob are playing a game on this graph. First Alice chooses to play as either "increasing" or "decreasing" for herself, and Bob gets the other choice. Then she places a token on any node of the graph. Bob then moves the token along any edge incident to that node. They now take turns playing the following game, with Alice going first.The current player must move the token from the current vertex to some adjacent unvisited vertex. Let w be the last weight of the last edge that was traversed. The edge that is traversed must be strictly greater than w if the player is playing as "increasing", otherwise, it must be strictly less. The first player unable to make a move loses.You are given n and the edge weights of the graph. You can choose to play as either Alice or Bob, and you will play against the judge. You must win all the games for your answer to be judged correct. | ['games', 'interactive'] | import sys
def stable_marriage(p1, p2):
n = len(p1)
ret = [-1 for __ in xrange(2*n)]
free = [True for __ in xrange(n)]
nfree = n
def engage(m,w):
ret[w+n] = m
ret[m] = w+n
free[m] = False
while nfree > 0:
m = next(i for i in xrange(n) if free[i])
idx = 0
while free[m]:
w = p1[m][idx]
if ret[w+n] == -1:
engage(m,w)
nfree -= 1
else:
m1 = ret[w+n]
if p2[w].index(m) < p2[w].index(m1):
free[m1] = True
ret[m1] = -1
engage(m,w)
idx += 1
return ret
def process_one():
n = int(raw_input())
grid = [map(int, raw_input().split()) for __ in xrange(n)]
print "B"
sys.stdout.flush()
x,d = raw_input().split()
d = int(d)
sign = -1 if ((x == 'I') ^ (d <= n)) else 1
partner = stable_marriage(
[sorted(range(n), key=lambda x: +sign*grid[i][x]) for i in xrange(n)],
[sorted(range(n), key=lambda x: -sign*grid[x][i]) for i in xrange(n)],
)
while True:
if d == -1: return
if d == -2: sys.exit(0)
print partner[d-1]+1
sys.stdout.flush()
d = int(raw_input())
t = int(raw_input())
for ___ in xrange(t):
process_one()
| Python | [
"games"
] | 1,334 | 1,357 | 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
} | 2,888 |
0939354d9bad8301efb79a1a934ded30 | A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals e. Volume of each vessel equals v liters. Of course, the amount of the water in any vessel cannot exceed v liters in the process of transfusions.Given the initial amounts ai of water in the vessels and the desired amounts bi find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2·n2. | ['constructive algorithms', 'dfs and similar', 'trees', 'graphs'] | n,v,e=map(int,raw_input().split())
a=[0]*(n+10)
b=[0]*(n+10)
E=[[] for i in xrange(n)]
f=[i for i in xrange(n)]
vis=[0]*(n+10)
ans=[]
rem=0
def fd(x):
if f[x]==x: return x
else:
f[x]=fd(f[x])
return f[x]
def dfs2(u,f,ty):
global rem
if rem<=a[u] and rem>0:
if ty==0: ans.append([u,f,rem])
else: ans.append([f,u,rem])
a[u]-=rem
a[f]+=rem
rem=0
else:
rem-=a[u]
for v in E[u]:
if v==f or vis[v]: continue
dfs2(v,u,ty)
if rem==0: break
if f!=-1:
if ty==0: ans.append([u,f,a[u]])
else: ans.append([f,u,a[u]])
a[f]+=a[u]
a[u]=0
def solve(c):
if a[c]==b[c]: return
global rem
if a[c]<b[c]:
rem=b[c]
dfs2(c,-1,0)
else:
for i in xrange(n): a[i],b[i]=v-a[i],v-b[i]
rem=b[c]
dfs2(c,-1,1)
for i in xrange(n): a[i],b[i]=v-a[i],v-b[i]
def dfs(u,f):
for v in E[u]:
if v==f: continue
dfs(v,u)
solve(u)
vis[u]=1
a=map(int,raw_input().split())
b=map(int,raw_input().split())
for i in xrange(e):
x,y=map(lambda x:int(x)-1,raw_input().split())
if fd(x)!=fd(y):
E[x].append(y)
E[y].append(x)
f[fd(x)]=fd(y)
for i in xrange(n):
if fd(i)!=i: continue
sa=sum(a[j] for j in xrange(n) if (fd(j)==i))
sb=sum(b[j] for j in xrange(n) if (fd(j)==i))
if sa!=sb:
print "NO"
exit()
dfs(i,-1)
print len(ans)
for c in ans:
print c[0]+1,c[1]+1,c[2]
| Python | [
"graphs",
"trees"
] | 663 | 1,306 | 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,991 |
5185f842c7c24d4118ae3661f4418a1d | Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).If it is possible to partition the array, also give any possible way of valid partitioning. | ['constructive algorithms', 'implementation', 'number theory', 'brute force'] | n,k,p=raw_input().strip().split(' ')
n,k,p=int(n),int(k),int(p)
arr=list(map(int,raw_input().strip().split(' ')))
odd=[j for j in arr if j&1]
even=[j for j in arr if not j&1]
if (k-p)>len(odd) or p>len(even)+(len(odd)-k+p)/2 or len(odd)%2!=(k-p)%2:
print 'NO'
else:
print 'YES'
count,j=0,0
while j<len(even) and count<p-1:
print 1,even[j]
j+=1
count+=1
i=1
while i<len(odd) and count<p-1:
print 2,odd[i],odd[i-1]
i+=2
count+=1
if count!=p and k-p==0:
print len(odd[i-1:])+len(even[j:]),
for i in odd[i-1:]:
print i,
for i in even[j:]:
print i
elif count!=p:
if j<len(even):
print 1,even[j]
j+=1
else:
print 2,odd[i],odd[i-1]
i+=2
count=0
i-=1
while j<len(even) and i<len(odd) and count<k-p-1:
print 2,odd[i],even[j]
i,j,count=i+1,j+1,count+1
while i<len(odd) and count<k-p-1:
print 1,odd[i]
count+=1
i+=1
if k-p!=0:
print len(odd[i:])+len(even[j:]),
for k in xrange(i,len(odd)):
print odd[k],
for t in xrange(j,len(even)):
print even[t],
| Python | [
"number theory"
] | 562 | 1,022 | 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,722 |
3c91df8d91562039d550f879570c8af1 | You are given an array a of length n. You are asked to process q queries of the following format: given integers i and x, multiply a_i by x.After processing each query you need to output the greatest common divisor (GCD) of all elements of the array a.Since the answer can be too large, you are asked to output it modulo 10^9+7. | ['brute force', 'data structures', 'hashing', 'implementation', 'math', 'number theory', 'sortings', 'two pointers'] | from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def fast_prime_factorization(n):
d = [(i + 1) % 2 * 2 for i in range(n + 1)]
d[0], d[1] = 0, 1
for i in range(3, n + 1):
if d[i]:
continue
for j in range(i, n + 1, 2 * i):
if not d[j]:
d[j] = i
return d
n, q = map(int, input().split())
a = list(map(int, input().split()))
mod = pow(10, 9) + 7
l = 2 * pow(10, 5) + 5
d = fast_prime_factorization(l)
cnt = [defaultdict(lambda : 0) for _ in range(l)]
j = 0
for i in a:
while i ^ d[i]:
cnt[d[i]][j] += 1
i //= d[i]
if i > 1:
cnt[i][j] += 1
j += 1
y = []
for _ in range(q):
i, x = map(int, input().split())
i -= 1
y.append((i, x))
while x ^ d[x]:
cnt[d[x]][i] += 1
x //= d[x]
if x > 1:
cnt[x][i] += 1
inf = pow(10, 9) + 1
mi = [0] * l
inv = [1] * l
ans0 = 1
for i in range(2, l):
if len(cnt[i]) ^ n:
continue
mi0 = min(j for j in cnt[i].values())
mi[i] = mi0
ans0 *= pow(i, mi0, mod)
ans0 %= mod
inv[i] = pow(i, mod - 2, mod)
ans = [ans0]
for i, x in reversed(y[1:]):
while x ^ d[x]:
cnt[d[x]][i] -= 1
if mi[d[x]] > cnt[d[x]][i]:
mi[d[x]] = cnt[d[x]][i]
ans0 *= inv[d[x]]
ans0 %= mod
x //= d[x]
if x > 1:
cnt[x][i] -= 1
if mi[x] > cnt[x][i]:
mi[d[x]] = cnt[x][i]
ans0 *= inv[x]
ans0 %= mod
ans.append(ans0)
sys.stdout.write("\n".join(map(str, reversed(ans)))) | Python | [
"math",
"number theory"
] | 382 | 1,697 | 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
} | 735 |
386345016773a06b9e190a55cc3717fa | Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros. | ['number theory', 'math'] | n = input()
if n < 3:
print '-1'
elif n == 3:
print 210
else :
x = pow(10, n - 1, 210)
y = 210 - x
print '1' + '0' * (n - 4) + "%03d" %y
| Python | [
"math",
"number theory"
] | 494 | 147 | 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,090 |
16c4160d1436206412ce51315cb6140b | Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty(): k = q.pop() # retrieve the first vertex from the queue a.append(k) # append k to the end of the sequence in which vertices were visited for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.Help Monocarp to find any tree with given visiting order a and minimum height. | ['greedy', 'graphs', 'trees', 'shortest paths'] | for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
d,c = [0]*n,0
for i in range(1,n):
if l[i-1] > l[i]:
c += 1
d[i] = d[c] + 1
print(d[n-1])
'''
5
1 2 5 4 3
'''
| Python | [
"graphs",
"trees"
] | 1,585 | 207 | 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
} | 41 |
c72d6f6b365354bea0c9cab81e34b395 | The only difference between this problem and D2 is the bound on the size of the tree.You are given an unrooted tree with n vertices. There is some hidden vertex x in that tree that you are trying to find.To do this, you may ask k queries v_1, v_2, \ldots, v_k where the v_i are vertices in the tree. After you are finished asking all of the queries, you are given k numbers d_1, d_2, \ldots, d_k, where d_i is the number of edges on the shortest path between v_i and x. Note that you know which distance corresponds to which query.What is the minimum k such that there exists some queries v_1, v_2, \ldots, v_k that let you always uniquely identify x (no matter what x is).Note that you don't actually need to output these queries. | ['brute force', 'constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees'] | #!/usr/bin/env python3
import sys
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline # to read input quickly
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
m9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
# d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = sys.maxsize
e18 = 10**18 + 10
# if testing locally, print to terminal with a different color
CHECK_OFFLINE_TEST = True
# CHECK_OFFLINE_TEST = False # uncomment this on Codechef
if CHECK_OFFLINE_TEST:
import getpass
OFFLINE_TEST = getpass.getuser() == "htong"
def log(*args):
if CHECK_OFFLINE_TEST and OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def solve(*args):
# screen input
if OFFLINE_TEST:
log("----- solving ------")
log(*args)
log("----- ------- ------")
return solve_(*args)
def read_matrix(rows):
return [list(map(int,input().split())) for _ in range(rows)]
def read_strings(rows):
return [input().strip() for _ in range(rows)]
def minus_one(arr):
return [x-1 for x in arr]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
def dfs(start, g, entry_operation, exit_operation):
# https://codeforces.com/contest/1646/submission/148435078
# https://codeforces.com/contest/1656/submission/150799881
entered = set([start])
exiting = set()
stack = [start]
prev = {}
null_pointer = "NULL"
prev[start] = null_pointer
while stack:
cur = stack[-1]
if cur not in exiting:
for nex in g[cur]:
if nex in entered:
continue
entry_operation(prev[cur], cur, nex)
entered.add(nex)
stack.append(nex)
prev[nex] = cur
exiting.add(cur)
else:
stack.pop()
exit_operation(prev[cur], cur)
def solve_(mrr, n):
# sum of minus one
# your solution here
g = defaultdict(set)
for a,b in mrr:
g[a].add(b)
g[b].add(a)
if n <= 2:
return n-1
log(g)
for i in range(n):
if len(g[i]) == 2:
a,b = g[i]
g[a].remove(i)
g[b].remove(i)
g[a].add(b)
g[b].add(a)
log(g)
res = 0
for i in range(n):
cnt = 0
for nex in g[i]:
if len(g[nex]) == 1:
cnt += 1
res += max(0, cnt-1)
return res
# for case_num in [0]: # no loop over test case
# for case_num in range(100): # if the number of test cases is specified
for case_num in range(int(input())):
# read line as an integer
k = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# arr = input().split()
# read one line and parse each word as an integer
# a,b,c = list(map(int,input().split()))
# arr = list(map(int,input().split()))
# arr = minus_one(arr)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = read_matrix(k-1) # and return as a list of list of int
mrr = minus_one_matrix(mrr)
res = solve(mrr,k) # include input here
# print length if applicable
# print(len(res))
# parse result
# res = " ".join(str(x) for x in res)
# res = "\n".join(str(x) for x in res)
# res = "\n".join(" ".join(str(x) for x in row) for row in res)
# print result
# print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required
print(res)
| Python | [
"graphs",
"trees"
] | 815 | 3,931 | 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,868 |
ca417ff967dcd4594de66ade1a06acf0 | A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between 2 and 314! (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height i having probability 2 - i for all positive integers i. The floors of a skyscraper with height i are numbered 0 through i - 1.To speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the i-th floor of one skyscraper with the i-th floor of another skyscraper if and only if there are no skyscrapers between them that have an i-th floor.Alice and Bob decide to count the number of skyscrapers.Alice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.Bob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than h due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds 2i to his counter, where i is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.Consider the following example. There are 6 buildings, with heights 1, 4, 3, 4, 1, 2 from left to right, and h = 2. Alice begins with her counter at 1 and then adds 1 five times for a result of 6. Bob begins with his counter at 1, then he adds 1, 4, 4, and 2, in order, for a result of 12. Note that Bob ignores the highest zip line because of his fear of heights (h = 2). Bob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.When Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter. | ['dp', 'probabilities', 'math'] | s=raw_input()
n,h=map(int,raw_input().split())
if s == "Bob": print n;exit()
ans=n
ti=1.0
for i in xrange(1,h+1):
ti *= 0.5
if ti < 0.1**50: break
tj = 1.0/(1.0-ti)
for j in xrange(1,n+1):
tj *= 1.0-ti
ans += (n-j)*tj*(ti-0.5*ti*(1.0+(j-1.0)*ti/(1.0-ti)))
print ans
| Python | [
"math",
"probabilities"
] | 2,449 | 300 | 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
} | 2,676 |
2b611e202c931d50d8a260b2b45d4cd7 | You are given three positive (greater than zero) integers c, d and x. You have to find the number of pairs of positive integers (a, b) such that equality c \cdot lcm(a, b) - d \cdot gcd(a, b) = x holds. Where lcm(a, b) is the least common multiple of a and b and gcd(a, b) is the greatest common divisor of a and b. | ['dp', 'math', 'number theory'] | import sys
input = lambda: sys.stdin.readline().rstrip()
MAX = 2*(10**7) + 1
memo = {}
def get_divisors(x: int) -> list:
if x in memo:
return memo[x]
factori = []
while x > 1:
factori.append(min_fact[x])
x //= min_fact[x]
now = [1]
factori.sort()
for p in factori:
nxt = []
for i in now:
nxt.append(i*p)
if i % p:
nxt.append(i)
now = nxt
memo[x] = now
return now
def sieve_of_eratosthenes(n):
min_fact = [1] * (n + 1)
lst = [1] * (n+1)
for p in range(2, n + 1):
if min_fact[p] > 1:
continue
for i in range(p, n+1, p):
min_fact[i] = p
lst[i] *= 2
return min_fact, lst
min_fact, lst = sieve_of_eratosthenes(MAX)
t = int(input())
for _ in range(t):
c, d, x = map(int, input().split())
ans = 0
divs = get_divisors(x)
for g in divs:
tmp = (x + d*g)
if tmp % c == 0:
l = tmp // c
else:
continue
if l % g:
continue
n = l // g
ans += lst[n]
print(ans)
| Python | [
"math",
"number theory"
] | 381 | 1,147 | 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,067 |
9363df0735005832573ef4d17b6a8302 | Consider the array a composed of all the integers in the range [l, r]. For example, if l = 3 and r = 7, then a = [3, 4, 5, 6, 7].Given l, r, and k, is it possible for \gcd(a) to be greater than 1 after doing the following operation at most k times? Choose 2 numbers from a. Permanently remove one occurrence of each of them from the array. Insert their product back into a. \gcd(b) denotes the greatest common divisor (GCD) of the integers in b. | ['greedy', 'math', 'number theory'] | for i in range(int(input())):
a=list(map(int,input().split(' ')))
if a[0]==a[1]:
if a[0]!=1:
print('YES')
else:
print('NO')
else:
k=a[2]
if a[0]%2!=0:
d=1+(a[1]-a[0])//2
else:
d=(a[1]-a[0]+1)//2
if k>=d:
print('YES')
else:
print('NO') | Python | [
"math",
"number theory"
] | 545 | 390 | 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,559 |
6639d6c53951f8c1a8324fb24ef68f7a | Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes. | ['strings'] | n = int(input())
for i in range(n):
word = input()
if len(word)>10:
print(word[0]+str(len(word)-2)+word[-1])
else:
print(word) | Python | [
"strings"
] | 854 | 133 | 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,796 |
028882706ed58b61b4672fc3e76852c4 | Monocarp and Bicarp live in Berland, where every bus ticket consists of n digits (n is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first \frac{n}{2} digits of this ticket is equal to the sum of the last \frac{n}{2} digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from 0 to 9. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | ['greedy', 'games', 'math'] | n = int(input())
word = input()
tot = 0
for i in range(n):
if word[i] == '?':
inc = 9
else:
inc = 2 * int(word[i])
tot += (2 * (i < n//2) - 1) * inc
print(["Monocarp", "Bicarp"][tot == 0]) | Python | [
"math",
"games"
] | 975 | 216 | 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
} | 4,798 |
82c3c6b0190e0e098396bd9e6fb885d1 | Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.Given a graph G=(V,E), an independent set is a subset of vertices V' \subset V such that for every pair u,v \in V', (u,v) \not \in E (i.e. no edge in E connects two vertices from V').An edge-induced subgraph consists of a subset of edges E' \subset E and all the vertices in the original graph that are incident on at least one edge in the subgraph.Given E' \subset E, denote G[E'] the edge-induced subgraph such that E' is the edge set of the subgraph. Here is an illustration of those definitions: In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:Given a tree G=(V,E), calculate the sum of w(H) over all except null edge-induced subgraph H of G, where w(H) is the number of independent sets in H. Formally, calculate \sum \limits_{\emptyset \not= E' \subset E} w(G[E']).Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo 998,244,353. | ['dp', 'dfs and similar', 'trees'] | import sys
range = xrange
input = raw_input
MOD = 998244353
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)
leaf = 0
while len(coupl[leaf]) > 1:
leaf += 1
root = leaf
bfs = [root]
for node in bfs:
for nei in coupl[node]:
del coupl[nei][coupl[nei].index(node)]
bfs += coupl[node]
DP0 = [0]*n
DP2 = [0]*n
DP4 = [0]*n
DP6 = [0]*n
for node in reversed(bfs):
a = 1
for child in coupl[node]:
fac = (DP2[child] + DP4[child] + DP6[child]) % MOD
a = a * fac % MOD
DP0[node] = int(a)
c = 1
for child in coupl[node]:
fac = (DP4[child] + DP6[child]) % MOD
c = c * fac % MOD
DP4[node] = int((a - c) % MOD)
e = 1
for child in coupl[node]:
fac = (DP0[child] + DP2[child] + DP4[child] + DP6[child]) % MOD
e = e * fac % MOD
DP6[node] = DP2[node] = int(e)
print (DP4[root] + DP6[root] - 1) % MOD
| Python | [
"graphs",
"trees"
] | 1,241 | 1,082 | 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,313 |
e5e937f080b20eaec5f12f1784ae6427 | You are given an integer x. Can you make x by summing up some number of 11, 111, 1111, 11111, \ldots? (You can use any number among them any number of times).For instance, 33=11+11+11 144=111+11+11+11 | ['dp', 'math', 'number theory'] | for _ in range(int(input())):
N = int(input())
if N%11==0 or N%111==0:
print("YES")
else:
k = N//111
N %= 111
# print(N,k)
N %= 11
# print(N,k)
if N==0:
print("YES")
else:
if 11-N<=k:
print("YES")
else:
print("NO")
| Python | [
"math",
"number theory"
] | 234 | 359 | 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,618 |
3b8678d118c90d34c99ffa9259cc611f | A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i \in [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes.You have n binary strings s_1, s_2, \dots, s_n (each s_i consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers x, a, y, b such that 1 \le x, y \le n and 1 \le a \le |s_x| and 1 \le b \le |s_y| (where x and y are string indices and a and b are positions in strings s_x and s_y respectively), swap (exchange) the characters s_x[a] and s_y[b]. What is the maximum number of strings you can make palindromic simultaneously? | ['greedy', 'strings'] | #!/usr/bin/env python
import os
import operator
from collections import defaultdict
import sys
from io import BytesIO, IOBase
import bisect
# def power(x, p):
# res = 1
# while p:
# if p & 1:
# res = res * x % 1000000007
# x = x * x % 1000000007
# p >>= 1
# return res;
def main():
# n,m,k=map(int,input().split())
# A=[int(k) for k in input().split()]
# B=[int(k) for k in input().split()]
# a=[0]
# b=[0]
# for i in range(n):
# a.append(a[i]+A[i])
# for i in range(m):
# b.append(b[i]+B[i])
# ans=0
# j=m
# for i in range(n+1):
# if a[i]>k:
# break
# while b[j]>k-a[i]:
# j-=1
# ans=max(ans,i+j)
# #print(i,j)
# print(ans)
for _ in range(int(input())):
n=int(input())
even_odd=0
ans=0
odd=0
for i in range(n):
st=input()
if len(st)&1:
odd+=1
ans+=1
continue
o=0
z=0
for j in range(len(st)):
if st[j]=="1":
o+=1
else:
z+=1
if z&1==0:
ans+=1
else:
even_odd+=1
if even_odd & 1==1:
if odd==0:
even_odd-=1
print(ans+even_odd)
# n=int(input())
# arr=[int(k) for k in input().split()]
# odd=[]
# even=[]
# for i in range(2*n):
# if arr[i]%2==0:
# even.append(i+1)
# else:
# odd.append(i+1)
# if len(odd)%2!=0 and len(even)%2!=0:
# odd.pop()
# even.pop()
# for i in range(0,len(odd),2):
# print(odd[i],odd[i+1])
# for i in range(0,len(even),2):
# print(even[i],even[i+1])
# else:
# if len(odd)!=0 and len(even)!=0:
# odd.pop()
# odd.pop()
# for i in range(0, len(odd), 2):
# print(odd[i], odd[i + 1])
# for i in range(0, len(even), 2):
# print(even[i], even[i + 1])
# else:
# for i in range(0,2*n-2,2):
# print(i+1,i+2)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main() | Python | [
"strings"
] | 975 | 4,068 | 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,303 |
4840c4ddf8d9ca82c6e8fcf71802539a | Everyone was happy coding, until suddenly a power shortage happened and the best competitive programming site went down. Fortunately, a system administrator bought some new equipment recently, including some UPSs. Thus there are some servers that are still online, but we need all of them to be working in order to keep the round rated.Imagine the servers being a binary string s of length n. If the i-th server is online, then s_i = 1, and s_i = 0 otherwise.A system administrator can do the following operation called electricity spread, that consists of the following phases: Select two servers at positions 1 \le i < j \le n such that both are online (i.e. s_i=s_j=1). The spread starts only from online servers. Check if we have enough power to make the spread. We consider having enough power if the number of turned on servers in range [i, j] is at least the number of turned off servers in range [i, j]. More formally, check whether 2 \cdot (s_i + s_{i+1} + \ldots + s_j) \ge j - i + 1. If the check is positive, turn on all the offline servers in range [i, j]. More formally, make s_k := 1 for all k from i to j. We call a binary string s of length n rated if we can turn on all servers (i.e. make s_i = 1 for 1 \le i \le n) using the electricity spread operation any number of times (possibly, 0). Your task is to find the number of rated strings of length n modulo m. | ['combinatorics', 'dp', 'math', 'strings'] | n, m = map(int, input().split())
def modmul(a, b, c = 0):
return (a * b + c) % m
half = [0, 0, 1] + [0] * (3 * n)
pref = [0, 0, 1] + [0] * (3 * n)
good = [-1, 1]
bad = [-1, 0]
for i in range(2, n + 1):
nb = 0
for j in range(1, i):
prev = i - 2 * j - 1
if prev < 0:
continue
add = modmul(pref[prev], good[j])
nb += add
half[j + i] += add
half[j + i] %= m
pref[i] = (pref[i - 1] + half[i]) % m
nb %= m
bad.append(nb)
tot = pow(2, i-2, m)
good.append((tot - nb) % m)
half[2 * i] += good[i]
print(good[n] % m)
| Python | [
"math",
"strings"
] | 1,516 | 653 | 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
} | 740 |
44beeb4ad160d9d58267e3f88fc44cd8 | Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges they’ve given to one another, their score is equal and they’re both desperately trying to best the other in various games of wits. This time, Dexterina challenged Womandark to a game of Nim.Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects from a single heap. The player who can't make a turn loses. By their agreement, the sizes of piles are selected randomly from the range [0, x]. Each pile's size is taken independently from the same probability distribution that is known before the start of the game.Womandark is coming up with a brand new and evil idea on how to thwart Dexterina’s plans, so she hasn’t got much spare time. She, however, offered you some tips on looking fabulous in exchange for helping her win in Nim. Your task is to tell her what is the probability that the first player to play wins, given the rules as above. | ['games', 'probabilities', 'matrices'] |
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,x=map(int,input().split())
def mult(a,b):
# compute a*b
c=[0]*128
for i in range(128):
for j in range(128):
c[i^j]+=a[i]*b[j]
return c
def quickpow(a,b):
# compute a**b
if b==1:
return a
if b&1:
return mult(quickpow(mult(a,a),b//2),a)
return quickpow(mult(a,a),b//2)
prob=list(map(float,input().split()))
prob+=[0.0]*(128-len(prob))
print("%.9f"%(1-quickpow(prob,n)[0])) | Python | [
"math",
"games",
"probabilities"
] | 1,228 | 510 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 0
} | 4,911 |
600b322b10cbde66ad8ffba5dc7d84e6 | As the name of the task implies, you are asked to do some work with segments and trees.Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.You are given n segments [l_1, r_1], [l_2, r_2], \dots, [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one.For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not.Determine if the resulting graph is a tree or not. | ['data structures', 'dsu', 'trees', 'graphs'] | import sys
range = xrange
input = raw_input
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
A = [0]*(2 * n)
L = []
R = []
for i in range(n):
l = inp[ii] - 1; ii += 1
r = inp[ii] - 1; ii += 1
L.append(l)
R.append(r)
A[l] = i
A[r] = ~i
class segtree:
def __init__(self, n):
m = 1
while m < n: m *= 2
self.m = m
self.data = [0]*(2 * m)
def add(self, i):
i += self.m
while i:
self.data[i] += 1
i >>= 1
def finder(self, l, r):
m = self.m
data = self.data
l += m
r += m
cand = []
while l < r:
if l & 1:
if data[l]:
cand.append(l)
l += 1
if r & 1:
r -= 1
if data[r]:
cand.append(r)
l >>= 1
r >>= 1
ans = []
for i in cand:
while i < m and data[i]:
if data[2 * i]:
cand.append(2 * i)
i = 2 * i + 1
if data[i]:
ans.append(i - m)
return ans
coupl = [[] for _ in range(n)]
seg = segtree(2 * n)
edges = 0
for j in range(2 * n):
i = A[j]
if i >= 0:
for r_ind in seg.finder(j, R[i]):
node = ~A[r_ind]
coupl[i].append(node)
coupl[node].append(i)
edges += 1
if edges == n:
print 'NO'
sys.exit()
seg.add(R[i])
if edges != n - 1:
print 'NO'
sys.exit()
found = [0]*n
found[0] = 1
bfs = [0]
for node in bfs:
for nei in coupl[node]:
if not found[nei]:
found[nei] = 1
bfs.append(nei)
if all(found):
print 'YES'
else:
print 'NO'
| Python | [
"graphs",
"trees"
] | 1,021 | 1,859 | 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,123 |
6a3043daecdb0442f4878ee08a8b70ba | We are sum for we are manySome NumberThis version of the problem differs from the previous one only in the constraint on t. You can make hacks only if both versions of the problem are solved.You are given two positive integers l and r.Count the number of distinct triplets of integers (i, j, k) such that l \le i < j < k \le r and \operatorname{lcm}(i,j,k) \ge i + j + k.Here \operatorname{lcm}(i, j, k) denotes the least common multiple (LCM) of integers i, j, and k. | ['brute force', 'data structures', 'math', 'number theory', 'two pointers'] | n = int(2e5+5)
ft = [0]*n
def update(i, val):
while i<n:
ft[i]-=val
i+=(i&(-i))
return
def query(i):
ans = 0
while i!=0:
ans += ft[i]
i -=(i&(-i))
return ans
cnt = [0 for i in range(n)]
pre = [0 for i in range(n)]
for i in range(1,n):
for j in range(i+i, n, i):
cnt[j] += 1
pre[i] = pre[i-1] + (cnt[i]*(cnt[i]-1))/2
for i in range(1, n):
ft[i]=pre[i]-pre[i-(i&(-i))]
vec = []
t = int(input())
ans = [0 for i in range(t+1)]
for _ in range(t):
arr = list(map(int, input().split()))
arr.append(_)
vec.append(arr)
vec.sort()
l = 1
for i in range(t):
r = vec[i][1]
while l< vec[i][0]:
for j in range(2*l, n, l):
cnt[j]-=1
update(j, cnt[j])
l+=1
m = r-l+1
ans[vec[i][2]]=query(r);
ans[vec[i][2]]+=max(r//6-(l+2)//3+1,0)
ans[vec[i][2]]+=max(r//15-(l+5)//6+1,0)
ans[vec[i][2]]=(m*(m-1)*(m-2))//6-ans[vec[i][2]]
for i in range(t):
print(int(ans[i]))
| Python | [
"math",
"number theory"
] | 534 | 1,002 | 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,698 |
401708ea0b55b933ad553977011460b4 | The Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders); an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders); a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different. | ['two pointers', 'games'] | import sys
range = xrange
input = raw_input
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
t = inp[ii]; ii += 1
for _ in range(t):
n = inp[ii]; ii += 1
x = inp[ii]; ii += 1
y = inp[ii]; ii += 1
z = inp[ii]; ii += 1
A = inp[ii: ii + n]; ii += n
memor = {}
def mexor(val, i):
if val <= 0:
return 0
if ((val, i)) not in memor:
A = []
A.append(mexor(val - x, 0))
if i != 1:
A.append(mexor(val - y, 1))
if i != 2:
A.append(mexor(val - z, 2))
if 0 not in A:
ans = 0
elif 1 not in A:
ans = 1
elif 2 not in A:
ans = 2
else:
ans = 3
memor[(val, i)] = ans
return memor[(val, i)]
AA = [mexor(i, 0) for i in range(250)]
BB = [mexor(i, 1) for i in range(250)]
CC = [mexor(i, 2) for i in range(250)]
aper = 70
while aper and AA[125 : 125 + aper] != AA[125 + aper : 125 + 2 * aper]:
aper -= 1
bper = 70
while bper and BB[125 : 125 + bper] != BB[125 + bper : 125 + 2 * bper]:
bper -= 1
cper = 70
while cper and CC[125 : 125 + cper] != CC[125 + cper : 125 + 2 * cper]:
cper -= 1
def mexor(val, i):
if val <= 0:
return 0
if i == 0:
if val < 250:
return AA[val]
else:
return AA[125 + (val - 125) % aper]
elif i == 1:
if val < 250:
return BB[val]
else:
return BB[125 + (val - 125) % bper]
else:
if val < 250:
return CC[val]
else:
return CC[125 + (val - 125) % cper]
xor = 0
for a in A:
xor ^= mexor(a, 0)
ways = 0
for a in A:
newxor = xor ^ mexor(a, 0)
if mexor(a - x, 0) == newxor:
ways += 1
if mexor(a - y, 1) == newxor:
ways += 1
if mexor(a - z, 2) == newxor:
ways += 1
print ways
| Python | [
"games"
] | 2,145 | 2,128 | 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
} | 597 |
86dc5cb9e667fc2ae4d988613feddcb6 | Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us! | ['math'] | p, k = map(int, input().split())
u = 10 * k - 1
v = pow(10, p - 1, u) - k
for y in range(k, 10):
if (y * v) % u == 0:
q = d = 9 * y
while q % u: q = 10 * q + d
q = str(q // u)
print(q * (p // len(q)))
break
else: print('Impossible')
| Python | [
"math"
] | 845 | 277 | 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,906 |
57f0f36905d7769167b7ba9d3d9be351 | This problem is a simplified version of D2, but it has significant differences, so read the whole statement.Polycarp has an array of n (n is even) integers a_1, a_2, \dots, a_n. Polycarp conceived of a positive integer k. After that, Polycarp began performing the following operations on the array: take an index i (1 \le i \le n) and reduce the number a_i by k.After Polycarp performed some (possibly zero) number of such operations, it turned out that all numbers in the array became the same. Find the maximum k at which such a situation is possible, or print -1 if such a number can be arbitrarily large. | ['math', 'number theory'] | def hcf(a,b):
if b>a:
a,b=b,a
if b==0:
return a
return hcf(b,a%b)
for iiii in range(int(input())):
n=int(input())
q=list(map(int,input().split()))
maxx=-1
q1=[]
q.sort()
for i in range(1,n):
if q[i]-q[i-1]>0:
q1.append(q[i]-q[i-1])
if len(q1)==0:
print(-1)
continue
if len(q1)==1:
print(q1[0])
continue
maxx=q1[0]
for i in range(1,len(q1)):
maxx=min(maxx,hcf(q1[0],q1[i]))
print(maxx) | Python | [
"math",
"number theory"
] | 668 | 544 | 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,321 |
9756e5dfba8ccfe96d854b36745e13d8 | Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], \ldots, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself.A travel on this graph works as follows. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. The next vertex is e_i[x] where x is an integer 0 \le x \le m_i-1 satisfying x \equiv c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly.For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 \le x \le 1) where x \equiv c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on.Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. | ['dp', 'graphs', 'number theory', 'math', 'implementation', 'data structures', 'dfs and similar', 'brute force'] | import io, sys
input = lambda f=io.StringIO(sys.stdin.buffer.read().decode()).readline: f().rstrip()
LCM = 2520
n = int(input())
k = list(map(int, input().split()))
m, e = [], []
for _ in range(n):
m.append(int(input()))
e.append(list(map(int, input().split())))
nxt = []
for i in range(n):
for j in range(LCM):
x = (j + k[i]) % LCM
y = e[i][x % m[i]] - 1
nxt.append(y * LCM + x)
mark = [-1] * (n * LCM)
loop = [None] * (n * LCM)
for i in range(n * LCM):
if loop[i]: continue
start = cur = i
rec = []
while True:
if mark[cur] != -1:
break
mark[cur] = i
rec.append(cur)
cur = nxt[cur]
if loop[cur]:
for u in rec:
loop[u] = loop[cur]
else:
uniq = set()
inloop = 0
for u in rec:
loop[u] = uniq
if u == cur:
inloop = 1
if inloop:
uniq.add(u // LCM)
out = []
for _ in range(int(input())):
x, y = map(int, input().split())
out.append(len(loop[(x - 1) * LCM + y % LCM]))
print(*out, sep='\n') | Python | [
"graphs",
"number theory",
"math"
] | 1,882 | 1,113 | 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
} | 910 |
3035265a44fcc3bb6317bf1b9662fc76 | Long ago, you thought of two finite arithmetic progressions A and B. Then you found out another sequence C containing all elements common to both A and B. It is not hard to see that C is also a finite arithmetic progression. After many years, you forgot what A was but remember B and C. You are, for some reason, determined to find this lost arithmetic progression. Before you begin this eternal search, you want to know how many different finite arithmetic progressions exist which can be your lost progression A. Two arithmetic progressions are considered different if they differ in their first term, common difference or number of terms.It may be possible that there are infinitely many such progressions, in which case you won't even try to look for them! Print -1 in all such cases. Even if there are finite number of them, the answer might be very large. So, you are only interested to find the answer modulo 10^9+7. | ['combinatorics', 'math', 'number theory'] | import sys
ipt=sys.stdin.readline
def sq(x):
st=0
en=10**10
while st<en:
y=(st+en)//2+1
if y**2>x:
en=y-1
else:
st=y
return st
def gcd(xx, yy):
return xx if yy==0 else gcd(yy, xx%yy)
mod=10**9+7
T=int(ipt())
for _ in range(T):
b, q, y=map(int, ipt().split())
c, r, z=map(int, ipt().split())
if r%q or b>c or (b+q*(y-1))<(c+r*(z-1)) or (c-b)%q:
print(0)
continue
if c-r<b or c+z*r>b+(y-1)*q:
print(-1)
continue
ans=0
for i in range(1, sq(r)+1):
if r%i==0:
if i**2==r:
if r==q*i//gcd(q, i):
ans=(ans+i**2)%mod
else:
if r==q*i//gcd(q, i):
ans=(ans+(r//i)**2)%mod
if r==q*(r//i)//gcd(q, r//i):
ans=(ans+i**2)%mod
print(ans) | Python | [
"math",
"number theory"
] | 995 | 927 | 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,288 |
a240eefaf9f3f35de9ea9860302b96d9 | This is the easy version of the problem. The only difference is maximum value of a_i.Once in Kostomuksha Divan found an array a consisting of positive integers. Now he wants to reorder the elements of a to maximize the value of the following function: \sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i), where \operatorname{gcd}(x_1, x_2, \ldots, x_k) denotes the greatest common divisor of integers x_1, x_2, \ldots, x_k, and \operatorname{gcd}(x) = x for any integer x.Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you. | ['dp', 'number theory'] | import sys
input = sys.stdin.readline
n=int(input())
A=list(map(int,input().split()))
MAX=max(A)+3
# エラトステネスの篩
# Sieve[i]で、iの最も小さい約数を返す。
Sieve=[i for i in range(MAX)]
for i in range(2,MAX):
if Sieve[i]!=i:
continue
for j in range(i,MAX,i):
if Sieve[j]==j:
Sieve[j]=i
# 素因数分解
def fact(x):
D=dict()
while x!=1:
k=Sieve[x]
if k in D:
D[k]+=1
else:
D[k]=1
x//=k
return D
# 約数列挙
def faclist(x):
LIST=[1]
while x!=1:
k=Sieve[x]
count=0
while x%k==0:
count+=1
x//=k
LIST2=[]
for i in range(count+1):
for l in LIST:
LIST2.append(l*k**i)
LIST=LIST2
return LIST
ANS=[0]*(MAX)
DP=[-1]*(MAX)
for a in A:
for x in faclist(a):
ANS[x]+=1
DP[x]=0
DP[1]=ANS[1]
for i in range(2,MAX):
if DP[i]==-1:
continue
for k in faclist(i):
DP[i]=max(DP[i],DP[k]+ANS[i]*(i-k))
print(max(DP))
| Python | [
"number theory"
] | 769 | 1,143 | 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
} | 711 |
c4609bd2b4652cb5c2482b16909ec64a | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | ['dp', 'combinatorics', 'probabilities'] | #!/usr/bin/python3
import sys
class CumTree:
def __init__(self, a, b):
self.a = a
self.b = b
self.count = 0
if a == b:
return
mid = (a + b) // 2
self.levo = CumTree(a, mid)
self.desno = CumTree(mid+1, b)
def manjsi(self, t):
if self.a >= t:
return 0
if self.b < t:
return self.count
return self.levo.manjsi(t) + self.desno.manjsi(t)
def vstavi(self, t):
if self.a <= t <= self.b:
self.count += 1
if self.a == self.b:
return
self.levo.vstavi(t)
self.desno.vstavi(t)
n = int(sys.stdin.readline())
p = [int(x) for x in sys.stdin.readline().strip().split()]
ct = CumTree(1, 4096)
vsota = 0
while len(p) > 0:
x = p.pop()
vsota += ct.manjsi(x)
ct.vstavi(x)
k, d = vsota // 2, vsota % 2
print("%f" % (4*k + d))
| Python | [
"math",
"probabilities"
] | 1,343 | 949 | 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
} | 82 |
7c721cdb8e5709bba242957344851d48 | This is an interactive problem.Alice and Bob are playing a game. There is n\times n grid, initially empty. We refer to the cell in row i and column j by (i, j) for 1\le i, j\le n. There is an infinite supply of tokens that come in 3 colors labelled 1, 2, and 3.The game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it a. Then, Bob chooses a color b\ne a, chooses an empty cell, and places a token of color b on that cell.We say that there is a conflict if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge.If at any moment there is a conflict, Alice wins. Otherwise, if n^2 turns are completed (so that the grid becomes full) without any conflicts, Bob wins.We have a proof that Bob has a winning strategy. Play the game as Bob and win.The interactor is adaptive. That is, Alice's color choices can depend on Bob's previous moves. | ['constructive algorithms', 'games', 'graphs', 'interactive'] | n=int(input())
black=[]
white=[]
for i in range(1,n+1):
for j in range(1,n+1):
if (i+j)%2:
white.append((i,j))
else:
black.append((i,j))
move=0
while move<n**2:
p=int(input())
move+=1
if p==1:
if black:
x,y=black.pop()
print(2,x,y)
else :
x,y=white.pop()
print(3,x,y)
elif p==2:
if white:
x,y=white.pop()
print(1,x,y)
else :
x,y=black.pop()
print(3,x,y)
else :
if black:
x,y=black.pop()
print(2,x,y)
else:
x,y=white.pop()
print(1,x,y)
| Python | [
"graphs",
"games"
] | 1,046 | 739 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,958 |
e01cf98c203b8845312ce30af70d3f2e | A famous sculptor Cicasso goes to a world tour!Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country — Berland.Cicasso is very devoted to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has "favourites". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help. There are n cities and m one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities — will be the largest. Note that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: . Four cities in the order of visiting marked as overlines: [1, 5, 2, 4].Note that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do. | ['shortest paths', 'graphs'] | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from heapq import heappop, heappush
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
INF = float('inf')
def bfs(graph, start=0):
used = [False] * len(graph)
used[start] = True
dist = [0] * len(graph)
q = [start]
for v in q:
for w in graph[v]:
if not used[w]:
dist[w] = dist[v] + 1
used[w] = True
q.append(w)
return dist, q[-3:]
def main():
n, m = map(int, input().split())
rev_graph = [set() for _ in range(n)]
graph = [set() for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
if u == v:
continue
graph[u - 1].add(v - 1)
rev_graph[v - 1].add(u - 1)
adj = [[0] * n for _ in range(n)]
best_to = [[0] * 3 for _ in range(n)]
best_from = [[0] * 3 for _ in range(n)]
for i in range(n):
adj[i], best_from[i] = bfs(graph, i)
_, best_to[i] = bfs(rev_graph, i)
best_score = 0
sol = (-1, -1, -1, -1)
for c2 in range(n):
for c3 in range(n):
if not adj[c2][c3] or c2 == c3:
continue
for c1 in best_to[c2]:
if c1 in [c2, c3]:
continue
for c4 in best_from[c3]:
if c4 in [c1, c2, c3]:
continue
score = adj[c1][c2] + adj[c2][c3] + adj[c3][c4]
if score > best_score:
best_score = score
sol = (c1 + 1, c2 + 1, c3 + 1, c4 + 1)
print(*sol)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| Python | [
"graphs"
] | 2,097 | 4,041 | 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
} | 3,726 |
4aaeff1b38d501daf9a877667e075d49 | Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n. Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.A cyclic shift of a permutation (p_1, p_2, \ldots, p_n) is a permutation (p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, \ldots, a_{i_k} for some i_1, i_2, \ldots, i_k such that l \leq i_1 < i_2 < \ldots < i_k \leq r. | ['dp', 'math', 'data structures', 'dfs and similar', 'trees'] | import sys
class segmentTree:
def __init__(self, n):
self.n = n
self.seg = [self.n + 1] * (self.n << 1)
def update(self, p, value):
p += self.n
self.seg[p] = value
while p > 1:
p >>= 1
self.seg[p] = min(self.seg[p * 2], self.seg[p * 2 + 1])
def query(self, l, r):
res = self.n
l += self.n
r += self.n
while l < r:
if l & 1:
res = min(res, self.seg[l])
l += 1
if r & 1:
res = min(res, self.seg[r - 1])
r -= 1
l >>= 1
r >>= 1
return res
inp = [int(x) for x in sys.stdin.read().split()]
n, m, q = inp[0], inp[1], inp[2]
p = [inp[idx] for idx in range(3, n + 3)]
index_arr = [0] * (n + 1)
for i in range(n): index_arr[p[i]] = i
a = [inp[idx] for idx in range(n + 3, n + 3 + m)]
leftmost_pos = [m] * (n + 1)
next = [-1] * m
for i in range(m - 1, -1, -1):
index = index_arr[a[i]]
right_index = 0 if index == n - 1 else index + 1
right = p[right_index]
next[i] = leftmost_pos[right]
leftmost_pos[a[i]] = i
log = 0
while (1 << log) <= n: log += 1
log += 1
dp = [[m for _ in range(m + 1)] for _ in range(log)]
for i in range(m):
dp[0][i] = next[i]
for j in range(1, log):
for i in range(m):
dp[j][i] = dp[j - 1][dp[j - 1][i]]
tree = segmentTree(m)
for i in range(m):
p = i
len = n - 1
for j in range(log - 1, -1, -1):
if (1 << j) <= len:
p = dp[j][p]
len -= (1 << j)
tree.update(i, p)
inp_idx = n + m + 3
ans = []
for i in range(q):
l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1
inp_idx += 2
if tree.query(l, r + 1) <= r:
ans.append('1')
else:
ans.append('0')
print(''.join(ans)) | Python | [
"math",
"graphs",
"trees"
] | 1,203 | 1,595 | 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
} | 779 |
d3a0402de1338a1a542a86ac5b484acc | There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not. | ['dp', 'number theory', 'math'] | n=int(input())
L=list(map(int,input().split()))
prime=[]
nn=n
i=2
while i*i<=n:
if nn%i==0:
prime.append(i)
while nn%i==0:
nn//=i
i+=1
#print(prime,nn)
if nn!=1:
prime.append(nn)
if prime[0]==2:
prime=prime[1:]
if n%4==0:
prime=[4]+prime
#print(prime)
out=False
for x in prime:
p=n//x
for i in range(p):
f=True
for j in range(i,n,p):
if not L[j]:
f=False
if f:
out=True
#print(p,i)
break
if out:
print("YES")
break
if not out:
print("NO")
| Python | [
"number theory",
"math"
] | 836 | 614 | 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,515 |
1f38c88f89786f118c65215d7df7bc9c | zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task! | ['dp', 'greedy', 'strings'] | lis=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
s = list(input())+['#']
n=len(s)
for i in range(1,n):
if s[i]==s[i-1]:
for j in lis:
if j!=s[i] and j!=s[i+1]:
s[i]=j
break
print(''.join(s[:-1]))
| Python | [
"strings"
] | 320 | 352 | 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,759 |
ad5b878298adea8742c36e2e119780f9 | Let F_k denote the k-th term of Fibonacci sequence, defined as below: F_0 = F_1 = 1 for any integer n \geq 0, F_{n+2} = F_{n+1} + F_nYou are given a tree with n vertices. Recall that a tree is a connected undirected graph without cycles.We call a tree a Fib-tree, if its number of vertices equals F_k for some k, and at least one of the following conditions holds: The tree consists of only 1 vertex; You can divide it into two Fib-trees by removing some edge of the tree. Determine whether the given tree is a Fib-tree or not. | ['brute force', 'dfs and similar', 'divide and conquer', 'number theory', 'trees'] | def main():
n = int(input())
graph = [[] for _ in range(n+1)]
parent = [-1 for _ in range(n+1)]
for _ in range(n-1):
x,y = map(int, input().split(' '))
graph[x].append(y)
graph[y].append(x)
digraph = [[] for _ in range(n+1)]
stack = [1]
count_order = []
while stack:
cur = stack.pop()
count_order.append(cur)
for adj in graph[cur]:
if parent[cur] == adj:
continue
stack.append(adj)
parent[adj] = cur
digraph[cur].append(adj)
count = [1 for _ in range(n+1)]
while count_order:
cur = count_order.pop()
for child in digraph[cur]:
count[cur] += count[child]
fib_numbers = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418]
fib_d = {val : i for i, val in enumerate(fib_numbers)}
fin = [0 for _ in range(n+1)]
def rec(cur_root, total_nodes):
if total_nodes <= 3:
return True
elif total_nodes not in fib_d:
return False
fib_idx = fib_d[total_nodes]
search_vals = [fib_numbers[fib_idx-1], fib_numbers[fib_idx-2]]
cut_node = -1
stack = [cur_root]
while stack:
cur_node = stack.pop()
if count[cur_node] in search_vals:
cut_node = cur_node
fin[cut_node] = True
break
for adj in digraph[cur_node]:
if not fin[adj]:
stack.append(adj)
if cut_node == -1:
return False
cut_node_count = count[cut_node]
# propagate update upwards
cur_parent = parent[cut_node]
while cur_parent != -1:
count[cur_parent] -= cut_node_count
cur_parent = parent[cur_parent]
parent[cut_node] = -1
if count[cur_root] <= count[cut_node]:
try1 = rec(cur_root, count[cur_root])
if try1:
return rec(cut_node, count[cut_node])
else:
try1 = rec(cut_node, count[cut_node])
if try1:
return rec(cur_root, count[cur_root])
return False
print("YES" if rec(1, n) else "NO")
# region fastio
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")
# endregion
if __name__ == "__main__":
main() | Python | [
"graphs",
"number theory",
"trees"
] | 581 | 4,230 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 1,118 |
ba9c136f84375cd317f0f8b53e3939c7 | The only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes n pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The i-th picture has a non-negative weight w_i, and the probability of the i-th picture being displayed is \frac{w_i}{\sum_{j=1}^nw_j}. That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add 1 to its weight; otherwise, she would subtract 1 from its weight.Nauuo will visit the website m times. She wants to know the expected weight of each picture after all the m visits modulo 998244353. Can you help her?The expected weight of the i-th picture can be denoted by \frac {q_i} {p_i} where \gcd(p_i,q_i)=1, you need to print an integer r_i satisfying 0\le r_i<998244353 and r_i\cdot p_i\equiv q_i\pmod{998244353}. It can be proved that such r_i exists and is unique. | ['dp', 'probabilities'] | P = 998244353
N, M = map(int, raw_input().split())
A = [int(a) for a in raw_input().split()]
B = [int(a) for a in raw_input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [1]
SU = li+di
PO = [0] * (5*M+10)
for i in range(-M-5, 2*M+5):
PO[i] = pow((SU+i)%P, P-2, P)
def calc(L):
su = sum(L)
pl = 0
pd = 0
RE = []
for i in range(len(L)):
a = li + i
b = di - (len(L) - 1 - i)
pd = b * L[i] * PO[a+b-SU]
RE.append((pl+pd)%P)
pl = a * L[i] * PO[a+b-SU]
RE.append(pl%P)
return RE
for i in range(M):
X = calc(X)
ne = 0
po = 0
for i in range(M+1):
po = (po + X[i] * (li + i)) % P
ne = (ne + X[i] * (di - M + i)) % P
invli = pow(li, P-2, P)
invdi = pow(di, P-2, P)
for i in range(N):
print(po * B[i] * invli % P if A[i] else ne * B[i] * invdi % P) | Python | [
"probabilities"
] | 1,318 | 878 | 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
} | 4,167 |
77e2a6ba510987ed514fed3bd547b5ab | You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. | ['greedy', 'strings'] | s = input()
bigger = 'a'
res = ''
for i in range(len(s)-1,-1,-1):
if s[i] >= bigger:
res = s[i] + res
bigger = s[i]
print(res) | Python | [
"strings"
] | 567 | 146 | 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,710 |
5a2c9caec9c20a3caed1982ee8ed8f9c | As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote. | ['combinatorics', 'probabilities', 'math'] | #!/usr/bin/python3.5
# -*- coding: utf-8 -*-
import json
import sys
def main():
n, m, k = map(int, input().strip().split())
if n + k < m:
print(0)
return
ans = 1.0
for i in range(k+1):
ans *= (m - i) * 1.0 / (n + i + 1)
print(1.0 - ans)
if __name__ == '__main__':
main() | Python | [
"math",
"probabilities"
] | 1,118 | 322 | 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
} | 4,796 |
9cd7f058d4671b12b67babd38293a3fc | Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex 1 is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left\lfloor\frac{w_i}{2}\right\rfloor).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make \sum\limits_{v \in leaves} w(root, v) \le S, where leaves is the list of all leaves.You have to answer t independent test cases. | ['data structures', 'dfs and similar', 'greedy', 'trees'] | import sys
from heapq import heappop, heapify
from collections import defaultdict
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
n, S = map(int, input().split())
adj = [dict() for _ in range(n+1)]
for _ in range(n-1):
u, v, w = map(int, input().split())
adj[u][v] = w
adj[v][u] = w
stack = [1]
dp = [0] * (n + 1)
dfs_order = []
parent = [0] * (n+1)
parent[1] = 1
while stack:
node = stack.pop()
dfs_order.append(node)
leaf = True
for next_node in adj[node].keys():
if parent[next_node] == 0:
parent[next_node] = node
stack.append(next_node)
leaf = False
if leaf:
dp[node] = 1
for node in reversed(dfs_order):
for next_node in adj[node].keys():
if next_node != parent[node]:
dp[node] += dp[next_node]
moves = []
s = 0
for v, c in enumerate(dp):
if v == 0 or v == 1:
continue
u = parent[v]
w = adj[u][v]
s += w * c
while w > 0:
moves.append((w//2 - w) * c)
w //= 2
heapify(moves)
ans = 0
while s - S > 0:
s += heappop(moves)
ans += 1
print(ans) | Python | [
"graphs",
"trees"
] | 1,424 | 1,319 | 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,324 |
f7f1d57921fe7b7a697967dcfc8f0169 | Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight. | ['data structures', 'number theory', 'math'] | import sys
range = xrange
# n log n time and memory precalc,
# then answers queries in O(1) time
class Queries:
def __init__(self, A, f = lambda a,b: a + b, max_d = float('inf')):
self.f = f
self.lists = [A]
n = len(A)
for d in range(1, min(n.bit_length(), max_d + 1)):
tmp = list(A)
self.lists.append(tmp)
x = (1 << d) + 1
jump = x + 1
I = (1 << d + 1) - 1
while x < n:
tmp[x] = f(tmp[x - 1], tmp[x])
tmp[x ^ I] = f(tmp[x ^ I], tmp[x - 1 ^ I])
x += 1 if ~x & I else jump
if x == n:
while x & I:
tmp[x ^ I] = f(tmp[x ^ I], tmp[x - 1 ^ I])
x += 1
def __call__(self, a, b):
tmp = self.lists[(a ^ b - 1).bit_length() - 1]
return self.f(tmp[a], tmp[b - 1]) if a - b + 1 else self.lists[0][a]
# n log log n time and memory precalc
# then answers queries in O(1) time
class Queries2:
def __init__(self, A, f = lambda a,b: a + b):
self.f = f
self.c = Queries(A, f, 3).__call__
n = len(A)
self.p = prefix = list(A)
self.s = suffix = list(A)
i = 17
while i < n:
prefix[i] = f(prefix[i - 1], prefix[i])
i += 1 + (~i & 15 == 0)
i = n - 2 if n - 2 & 15 != 15 else n - 3
while i >= 0:
suffix[i] = f(suffix[i], suffix[i + 1])
i -= 1 + (i & 15 == 0)
self.k = Queries(suffix[:-16: 16], f).__call__
def __call__(self, a, b):
if a ^ b - 1 < 16:
return self.c(a, b)
return self.f(self.f(self.s[a], self.k((a >> 4) + 1, b - 1 >> 4)) if (a >> 4) + 1 < b - 1 >> 4 else self.s[a], self.p[b - 1])
def gcd(a,b):
while a:
a,b = b % a, a
return b
def merge((val1, count1), (val2, count2)):
g = gcd(val1, val2)
if g == val1 == val2:
return g, count1 + count2
elif g == val1:
return g, count1
elif g == val2:
return g, count2
else:
return g, 0
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
S = inp[ii: ii + n]; ii += n
RQ = Queries2([(s,1) for s in S], merge)
t = inp[ii]; ii += 1
out = []
for _ in range(t):
l = inp[ii] - 1; ii += 1
r = inp[ii]; ii += 1
out.append(r - l - RQ(l,r)[1])
print '\n'.join(str(x) for x in out)
| Python | [
"number theory",
"math"
] | 959 | 2,439 | 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,543 |
2e01de6090e862f7f18a47dcbcb3be53 | It is given a non-negative integer x, the decimal representation of which contains n digits. You need to color each its digit in red or black, so that the number formed by the red digits is divisible by A, and the number formed by the black digits is divisible by B.At least one digit must be colored in each of two colors. Consider, the count of digits colored in red is r and the count of digits colored in black is b. Among all possible colorings of the given number x, you need to output any such that the value of |r - b| is the minimum possible.Note that the number x and the numbers formed by digits of each color, may contain leading zeros. Example of painting a number for A = 3 and B = 13 The figure above shows an example of painting the number x = 02165 of n = 5 digits for A = 3 and B = 13. The red digits form the number 015, which is divisible by 3, and the black ones — 26, which is divisible by 13. Note that the absolute value of the difference between the counts of red and black digits is 1, it is impossible to achieve a smaller value. | ['dfs and similar', 'dp', 'implementation', 'math', 'meet-in-the-middle'] | import sys
import io, os
input = sys.stdin.readline
from collections import defaultdict
def main():
t = int(input())
for _ in range(t):
n, a, b = map(int, input().split())
s = list(str(input().rstrip()))
s = [int(c) for c in s]
dp = [-1]*(a*b*(n+1)*(n+1))
dp[0] = 0
def getindex(i, j, ra, rb):
return i*(n+1)*a*b+j*a*b+ra*b+rb
for i, c in enumerate(s):
for j in range(i+1):
for ra in range(a):
for rb in range(b):
idx = getindex(i, j, ra, rb)
if dp[idx] == -1:
continue
#red
nra = (ra*10+c)%a
nidx =getindex(i+1, j+1, nra, rb)
dp[nidx] = idx
#black
nrb = (rb*10+c)%b
nidx =getindex(i+1, j, ra, nrb)
dp[nidx] = idx
bestj = 0
for j in range(1, n+1):
idx = getindex(n, j, 0, 0)
if dp[idx] != -1 and abs(j-(n-j)) < abs(bestj-(n-bestj)):
bestj = j
if bestj == 0:
print(-1)
continue
cur = n
j = bestj
ra = 0
rb = 0
ans = []
while cur > 0:
idx = getindex(cur, j, ra, rb)
pidx = dp[idx]
cur, r = divmod(pidx, (n+1)*a*b)
pj, r = divmod(r, a*b)
ra, rb = divmod(r, b)
if pj == j-1:
ans.append('R')
else:
ans.append('B')
j = pj
ans.reverse()
print(''.join(ans))
if __name__ == '__main__':
main()
| Python | [
"graphs",
"math"
] | 1,177 | 1,830 | 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,148 |
a1effd6a0f6392f46f6aa487158fef7d | You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i \le x \le r_i, and ((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a). Calculate the answer for each query.Recall that y \bmod z is the remainder of the division of y by z. For example, 5 \bmod 3 = 2, 7 \bmod 8 = 7, 9 \bmod 4 = 1, 9 \bmod 9 = 0. | ['number theory', 'math'] | import math
t = int(input())
def get(A,B,N):
if(N==-1):
return 0;
if(max(A,B) > N):
return N + 1
GCD = int(math.gcd(A,B))
X = GCD * (A//GCD) * (B//GCD)
Delta = min(max(A,B), N - N//X*X + 1)
return max(A,B) + max(N//X-1,0)*max(A,B) + (Delta * int(N>=X))
for _ in range(t):
a,b,q = map(int,input().split())
for _ in range(q):
l,r = map(int,input().split())
ans = abs(l-r) + 1 - (get(a,b,r) - get(a,b,l-1))
print(int(ans),end=' ')
print()
| Python | [
"math",
"number theory"
] | 504 | 514 | 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,021 |
42b425305ccc28b0d081b4c417fe77a1 | The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string s (which is initially a palindrome in this version) of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations: Choose any i (1 \le i \le n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw. | ['constructive algorithms', 'games'] | t = int(input())
while t:
int(input())
s = input().count('0')
if s%2 == 1 and s > 1: print('ALICE')
else: print('BOB')
t-=1 | Python | [
"games"
] | 1,371 | 149 | 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,873 |
f06f7d0dcef10f064f5ce1e9eccf3928 | You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel.For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o".For example of a not beautiful lyric, "hey man""iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. | ['data structures', 'greedy', 'strings'] | from sys import stdin, stdout
import sys, atexit, io
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write():
sys.__stdout__.write(buffer.getvalue())
@atexit.register
def main():
dici = {}
n = int(stdin.readline())
for k in xrange(n):
word = stdin.readline()
vog = ""
cont = 0
for l in word:
if l in ["a", "e", "i", "o", "u"]:
vog = l
cont += 1
if not (vog, cont) in dici:
dici[(vog, cont)] = [word]
else:
dici[(vog, cont)].append(word)
reject = {}
other = []
god = []
for l in dici:
if len(dici[l]) > 1:
for k in xrange(len(dici[l])-1, 0, -2):
other.append((dici[l][k], dici[l][k-1]))
dici[l].pop()
dici[l].pop()
for l in dici:
if len(dici[l]) == 1:
if not l[1] in reject:
reject[l[1]] = [dici[l][0]]
else:
reject[l[1]].append(dici[l][0])
for l in reject:
if len(reject[l]) > 1:
for k in xrange(len(reject[l])-1, 0, -2):
god.append((reject[l][k], reject[l][k-1]))
reject[l].pop()
reject[l].pop()
result = []
for k in xrange(min(len(other), len(god) )):
result.append(other[k])
result.append(god[k])
final = []
for k in xrange( 0,len(result), 2):
final.append( (result[k+1][1], result[k][1]))
final.append( (result[k+1][0], result[k][0]))
if (len(god) - len(other)) % 2 == 0:
for k in xrange(len(god), len(other), 2):
final.append( (other[k+1][1], other[k][1]))
final.append( (other[k+1][0], other[k][0]))
else:
for k in xrange(len(god) + 1, len(other), 2):
final.append( (other[k+1][1], other[k][1]))
final.append( (other[k+1][0], other[k][0]))
stdout.write("%d\n" % (len(final)/2))
for k in xrange(0, len(final), 2):
stdout.write(final[k][0] + final[k][1])
stdout.write(final[k+1][0] + final[k+1][1])
if __name__ == "__main__":
main
| Python | [
"strings"
] | 1,584 | 1,818 | 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,477 |
1d547a38250c7780ddcf10674417d5ff | Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of the region that will be cleared from snow. Help him. | ['binary search', 'geometry', 'ternary search'] | def dot_product(v1, v2):
return v1.x * v2.x + v1.y * v2.y
class vector:
def __init__(self, x, y):
self.x = x
self.y = y
def length(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def cross_product(self, v):
return self.x * v.y - self.y * v.x
class line:
def __init__(self, a, b):
self.a = a
self.b = b
def distance(self, p):
return abs(vector(p.x - self.a.x, p.y - self.a.y).cross_product(vector(p.x - self.b.x, p.y - self.b.y)) / vector(self.a.x - self.b.x, self.a.y - self.b.y).length())
class ray:
def __init__(self, a, b):
self.a = a
self.b = b
def distance(self, p):
if dot_product(vector(self.b.x - self.a.x, self.b.y - self.a.y), vector(p.x - self.a.x, p.y - self.a.y)) >= 0:
return line(self.a, self.b).distance(p)
return vector(self.a.x - p.x, self.a.y - p.y).length()
class segment:
def __init__(self, a, b):
self.a = a
self.b = b
def min_distance(self, p):
if dot_product(vector(self.b.x - self.a.x, self.b.y - self.a.y), vector(p.x - self.a.x, p.y - self.a.y)) >= 0:
return ray(self.b, self.a).distance(p)
return vector(self.a.x - p.x, self.a.y - p.y).length()
def max_distance(self, p):
return max(vector(self.a.x - p.x, self.a.y - p.y).length(), vector(self.b.x - p.x, self.b.y - p.y).length())
n, x, y = map(int, input().split())
p = vector(x, y)
min_r = 2000000
max_r = 0
a = [[] for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
a[i] = vector(a[i][0], a[i][1])
a[n] = a[0]
for i in range(n):
s = segment(a[i], a[i + 1])
min_r = min(min_r, s.min_distance(p))
max_r = max(max_r, s.max_distance(p))
pi = 3.141592653589
print(pi * max_r ** 2 - pi * min_r ** 2) | Python | [
"geometry"
] | 948 | 1,840 | 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
} | 3,746 |
e03bec836d52fe4784a5b4c62ab5b2c8 | Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.In his favorite math class, the teacher taught him the following interesting definitions.A parenthesis sequence is a string, containing only characters "(" and ")".A correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, parenthesis sequences "()()", "(())" are correct (the resulting expressions are: "(1+1)+(1+1)", "((1+1)+1)"), while ")(" and ")" are not. Note that the empty string is a correct parenthesis sequence by definition.We define that |s| as the length of string s. A strict prefix s[1\dots l] (1\leq l< |s|) of a string s = s_1s_2\dots s_{|s|} is string s_1s_2\dots s_l. Note that the empty string and the whole string are not strict prefixes of any string by the definition.Having learned these definitions, he comes up with a new problem. He writes down a string s containing only characters "(", ")" and "?". And what he is going to do, is to replace each of the "?" in s independently by one of "(" and ")" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.After all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable. | ['greedy', 'strings'] | from __future__ import print_function, division
from sys import stdin, exit
def no_ans():
print(":(")
exit(0)
n = int(stdin.readline())
s = [ch for ch in stdin.readline()[:n]]
if n % 2 == 1 or s[0] == ')' or s[-1] == '(':
no_ans()
s[0] = '('
s[-1] = ')'
cur_open = 0
open_left = (n - 1) // 2 - s[1:n - 1].count('(')
for i, char in enumerate(s[1:n - 1], 1):
if char == '(':
cur_open += 1
elif char == '?' and open_left > 0:
cur_open += 1
open_left -= 1
s[i] = '('
else:
cur_open -= 1
s[i] = ')'
if cur_open < 0:
no_ans()
if cur_open != 0:
no_ans()
print(''.join(s))
| Python | [
"strings"
] | 1,593 | 669 | 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
} | 55 |
581c89736e549300c566e4700b741906 | Alice and Bob play a game. Alice has n cards, the i-th of them has the integer a_i written on it. Bob has m cards, the j-th of them has the integer b_j written on it.On the first turn of the game, the first player chooses one of his/her cards and puts it on the table (plays it). On the second turn, the second player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the first turn, and plays it. On the third turn, the first player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the second turn, and plays it, and so on — the players take turns, and each player has to choose one of his/her cards with greater integer than the card played by the other player on the last turn.If some player cannot make a turn, he/she loses.For example, if Alice has 4 cards with numbers [10, 5, 3, 8], and Bob has 3 cards with numbers [6, 11, 6], the game may go as follows: Alice can choose any of her cards. She chooses the card with integer 5 and plays it. Bob can choose any of his cards with number greater than 5. He chooses a card with integer 6 and plays it. Alice can choose any of her cards with number greater than 6. She chooses the card with integer 10 and plays it. Bob can choose any of his cards with number greater than 10. He chooses a card with integer 11 and plays it. Alice can choose any of her cards with number greater than 11, but she has no such cards, so she loses. Both Alice and Bob play optimally (if a player is able to win the game no matter how the other player plays, the former player will definitely win the game).You have to answer two questions: who wins if Alice is the first player? who wins if Bob is the first player? | ['games', 'greedy'] | r='Alice','Bob'
R=lambda:max(map(int,input().split()))
for _ in[0]*R():R();a=R();R();b=R();print(r[a<b]+'\n'+r[a<=b]) | Python | [
"games"
] | 1,878 | 117 | 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
} | 3,317 |
d8134a016838448ed827233003626362 | You have a blackboard and initially only an odd number x is written on it. Your goal is to write the number 1 on the blackboard.You may write new numbers on the blackboard with the following two operations. You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the blackboard. The two numbers you have chosen remain on the blackboard. You may take two numbers (not necessarily distinct) already on the blackboard and write their bitwise XOR on the blackboard. The two numbers you have chosen remain on the blackboard. Perform a sequence of operations such that at the end the number 1 is on the blackboard. | ['constructive algorithms', 'number theory', 'bitmasks', 'math', 'matrices'] | #!/usr/bin/env python
from __future__ import division, print_function
from operator import *
import os
import sys
from io import BytesIO, IOBase
#from types import ModuleType
sys.setrecursionlimit(1 << 10)
class TailRecurseException(BaseException):
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs
# https://code.activestate.com/recipes/474088-tail-call-optimization-decorator/
def tail_call_optimized(g):
"""
This function decorates a function with tail call
optimization. It does this by throwing an exception
if it is it's own grandparent, and catching such
exceptions to fake the tail call optimization.
This function fails if the decorated
function recurses in a non-tail context.
"""
def func(*args, **kwargs):
f = sys._getframe()
if f.f_back and f.f_back.f_back and f.f_back.f_back.f_code == f.f_code:
raise TailRecurseException(args, kwargs)
else:
while 1:
try:
return g(*args, **kwargs)
except TailRecurseException as e:
args = e.args
kwargs = e.kwargs
func.__doc__ = g.__doc__
return func
def identity(g): return g
tco = identity
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
from collections import defaultdict
____dm = None
ONLINE_JUDGE = __debug__
def inputline():
global inp
inp = input().split()
inp.reverse()
def readint(): return int(inp.pop())
def readfloat(): return float(inp.pop())
def nextline(): return inputline()
def void(*arg): return None
displayln = print
println = print
if ONLINE_JUDGE:
dbgln = void
else:
dbgln = print
def add1(x): return x + 1
def sub1(x): return x - 1
def ceildiv(a, b): return -(-a // b)
def g231():
##@tco
def lo_0(x_1):
##@tco
def do_3(j_4):
g133 = gt(j_4, x_1)
if g133 != False:
return j_4
else:
g134 = mul(2, j_4)
return do_3(g134)
g135 = do_3
lb2_2 = g135(1)
##@tco
def do_5(i_6, j_7, t_8):
g136 = gt(j_7, x_1)
if g136 != False:
return t_8
else:
g137 = truediv(i_6, 2)
g138 = add(j_7, i_6)
g139 = add1(t_8)
return do_5(g137, g138, g139)
g140 = do_5
g141 = truediv(lb2_2, 4)
g142 = truediv(lb2_2, 2)
return g140(g141, g142, 0)
global cnt_9
cnt_9 = 120
##@tco
def solve_lo1_10(x_11):
global cnt_9
##@tco
def do_13(i_14, j_15):
g143 = gt(j_15, x_11)
if g143 != False:
return i_14
else:
g144 = add1(i_14)
g145 = mul(2, j_15)
return do_13(g144, g145)
g146 = do_13
btx_12 = g146(0, 1)
g147 = sub(btx_12, 1)
g148 = pow(2, g147)
y_16 = mul(x_11, g148)
i_17 = sub(btx_12, 1)
##@tco
def do_18(x_19, i_20):
global cnt_9
g149 = eq(i_20, 0)
if g149 != False:
return None
else:
g150 = sub1(cnt_9)
_151 = cnt_9 = g150
void()
print(x_19, "+", x_19)
g152 = mul(2, x_19)
g153 = sub(i_20, 1)
return do_18(g152, g153)
g154 = do_18
g154(x_11, i_17)
a_21 = add(y_16, x_11)
g155 = sub1(cnt_9)
_156 = cnt_9 = g155
void()
print(y_16, "+", x_11)
b_22 = xor(y_16, x_11)
g157 = sub1(cnt_9)
_158 = cnt_9 = g157
void()
print(y_16, "^", x_11)
c_23 = xor(a_21, b_22)
g159 = sub1(cnt_9)
_160 = cnt_9 = g159
void()
print(a_21, "^", b_22)
loc_24 = lo_0(c_23)
g161 = gt(loc_24, 1)
if g161 != False:
c2_25 = add(c_23, c_23)
a_27 = c_23
b_26 = c_23
g162 = sub1(cnt_9)
_163 = cnt_9 = g162
void()
print(a_27, "+", b_26)
q_28 = xor(c_23, c2_25)
a_29 = c_23
g164 = sub1(cnt_9)
_165 = cnt_9 = g164
void()
print(a_29, "^", c2_25)
g166 = pow(2, loc_24)
w_30 = mul(q_28, g166)
##@tco
def do_31(x_32, i_33):
global cnt_9
g167 = eq(i_33, 0)
if g167 != False:
return None
else:
g168 = sub1(cnt_9)
_169 = cnt_9 = g168
void()
print(x_32, "+", x_32)
g170 = mul(2, x_32)
g171 = sub(i_33, 1)
return do_31(g170, g171)
g172 = do_31
g172(q_28, loc_24)
qa_34 = add(q_28, w_30)
g173 = sub1(cnt_9)
_174 = cnt_9 = g173
void()
print(q_28, "+", w_30)
qb_35 = xor(q_28, w_30)
g175 = sub1(cnt_9)
_176 = cnt_9 = g175
void()
print(q_28, "^", w_30)
qc_36 = xor(qa_34, qb_35)
g177 = sub1(cnt_9)
_178 = cnt_9 = g177
void()
print(qa_34, "^", qb_35)
g179 = mul(2, q_28)
qd_37 = xor(qc_36, g179)
b_38 = mul(2, q_28)
g180 = sub1(cnt_9)
_181 = cnt_9 = g180
void()
print(qc_36, "^", b_38)
g182 = sub(loc_24, 1)
g183 = pow(2, g182)
qe_39 = mul(qd_37, g183)
i_40 = sub(loc_24, 1)
##@tco
def do_41(x_42, i_43):
global cnt_9
g184 = eq(i_43, 0)
if g184 != False:
return None
else:
g185 = sub1(cnt_9)
_186 = cnt_9 = g185
void()
print(x_42, "+", x_42)
g187 = mul(2, x_42)
g188 = sub(i_43, 1)
return do_41(g187, g188)
g189 = do_41
g189(qd_37, i_40)
qqq_44 = xor(q_28, qe_39)
g190 = sub1(cnt_9)
_191 = cnt_9 = g190
void()
print(q_28, "^", qe_39)
_192 = c_23 = qqq_44
void()
else:
None
g193 = sub(btx_12, 2)
g194 = pow(2, g193)
mul(c_23, g194)
x_46 = c_23
i_45 = sub(btx_12, 2)
##@tco
def do_47(x_48, i_49):
global cnt_9
g195 = eq(i_49, 0)
if g195 != False:
return None
else:
g196 = sub1(cnt_9)
_197 = cnt_9 = g196
void()
print(x_48, "+", x_48)
g198 = mul(2, x_48)
g199 = sub(i_49, 1)
return do_47(g198, g199)
g200 = do_47
g200(x_46, i_45)
##@tco
def do_51(i_52, k_53, j_54):
g201 = eq(i_52, c_23)
if g201 != False:
return j_54
else:
g202 = mul(2, i_52)
g203 = mul(2, k_53)
g204 = and_(j_54, i_52)
g205 = eq(g204, 0)
def g208():
global cnt_9
if g205 != False:
return j_54
else:
nj_55 = xor(j_54, k_53)
g206 = sub1(cnt_9)
_207 = cnt_9 = g206
void()
print(j_54, "^", k_53)
return nj_55
g208 = g208()
return do_51(g202, g203, g208)
g209 = do_51
g210 = mul(2, x_11)
global f_50
f_50 = g209(2, g210, x_11)
##@tco
def do_56(qq_57):
global f_50
global cnt_9
g211 = gt(qq_57, f_50)
if g211 != False:
return None
else:
g212 = and_(qq_57, f_50)
g213 = gt(g212, 0)
if g213 != False:
nf_58 = xor(qq_57, f_50)
b_59 = f_50
g214 = sub1(cnt_9)
_215 = cnt_9 = g214
void()
print(qq_57, "^", b_59)
_216 = f_50 = nf_58
void()
else:
None
g217 = mul(2, qq_57)
return do_56(g217)
g218 = do_56
return g218(c_23)
n_60 = readint()
print(120)
g219 = eq(n_60, 1)
if g219 != False:
None
else:
g220 = lo_0(n_60)
g221 = gt(g220, 1)
if g221 != False:
x2_61 = add(n_60, n_60)
g222 = sub1(cnt_9)
_223 = cnt_9 = g222
void()
print(n_60, "+", n_60)
y_62 = xor(n_60, x2_61)
g224 = sub1(cnt_9)
_225 = cnt_9 = g224
void()
print(n_60, "^", x2_61)
solve_lo1_10(y_62)
else:
solve_lo1_10(n_60)
@tail_call_optimized
def do_63(cnt_64):
global cnt_9
g226 = eq(cnt_64, 0)
if g226 != False:
return None
else:
g227 = sub1(cnt_9)
_228 = cnt_9 = g227
void()
print(n_60, "+", n_60)
g229 = sub1(cnt_64)
return do_63(g229)
g230 = do_63
return g230(cnt_9)
_232 = main = g231
void()
None
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
inputline()
main()
| Python | [
"number theory",
"math"
] | 675 | 12,207 | 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,567 |
f23d3e6ca1e4d7fbe5a2ca38ebb37c46 | You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree.You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, \ldots, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, \ldots, y_{k_2} in his labeling. The values of x_1, x_2, \ldots, x_{k_1} and y_1, y_2, \ldots, y_{k_2} are known to both of you. The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms: A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling. B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices. | ['dfs and similar', 'trees', 'interactive'] | import sys
from math import *
from random import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
e = [[] for i in range(n+1)]
p = [None]*(n+1)
my = [False]*(n+1)
for i in range(n-1):
a,b = mints()
e[a].append(b)
e[b].append(a)
def dfs(x):
for i in e[x]:
if p[i] == None:
p[i] = x
dfs(i)
k1 = mint()
x = list(mints())
for i in x:
my[i] = True
k2 = mint()
y = list(mints())
p[x[0]] = 0
dfs(x[0])
print('B',y[0])
sys.stdout.flush()
z = mint()
while my[z] != True:
z = p[z]
print('A',z)
sys.stdout.flush()
zz = mint()
if zz in y:
print('C',z)
else:
print('C',-1)
sys.stdout.flush()
t = mint()
for i in range(t):
solve()
| Python | [
"graphs",
"trees"
] | 1,500 | 777 | 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,080 |
3f1e2549d7342364b08f976fcbb7b1fa | When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 \times n grid where each row is a permutation of the numbers 1,2,3,\ldots,n.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. | ['combinatorics', 'dp', 'dsu', 'graphs', 'math'] | for i in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
d=dict(zip(a,b))
cnt=0
while d:
cnt+=1
k,v=d.popitem()
while v!=k:
v=d.pop(v)
print(pow(2,cnt,10**9+7)) | Python | [
"math",
"graphs"
] | 885 | 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
} | 1,404 |
56b207a6d280dc5ea39ced365b402a96 | Okabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren.Okabe's city is represented by a 2D grid of cells. Rows are numbered from 1 to n from top to bottom, and columns are numbered 1 to m from left to right. Exactly k cells in the city are lit by a street lamp. It's guaranteed that the top-left cell is lit.Okabe starts his walk from the top-left cell, and wants to reach the bottom-right cell. Of course, Okabe will only walk on lit cells, and he can only move to adjacent cells in the up, down, left, and right directions. However, Okabe can also temporarily light all the cells in any single row or column at a time if he pays 1 coin, allowing him to walk through some cells not lit initially. Note that Okabe can only light a single row or column at a time, and has to pay a coin every time he lights a new row or column. To change the row or column that is temporarily lit, he must stand at a cell that is lit initially. Also, once he removes his temporary light from a row or column, all cells in that row/column not initially lit are now not lit.Help Okabe find the minimum number of coins he needs to pay to complete his walk! | ['graphs', 'dfs and similar', 'shortest paths'] | from sys import stdin
from collections import deque
def main():
n, m, k = map(int, stdin.readline().split())
a = [map(int, stdin.readline().split()) for _ in xrange(k)]
row = [dict() for i in xrange(n + 10)]
col = [dict() for i in xrange(m + 10)]
inf = 10010001
d = [inf] * k
q = []
pu = q.append
for i in xrange(k):
r, c = a[i]
row[r][c] = i
col[c][r] = i
if r == c == 1:
d[i] = 0
pu(i)
done = [None] * k
while q:
v = []
for x in q:
r, c = a[x]
qq = deque()
qq.append(x)
done[x] = 1
while qq:
y = qq.popleft()
r, c = a[y]
for cc in (c-1, c+1):
if cc in row[r] and done[row[r][cc]] is None:
z = row[r][cc]
done[z] = 1
qq.append(z)
for rr in (r-1, r+1):
if rr in col[c] and done[col[c][rr]] is None:
z = col[c][rr]
done[z] = 1
qq.append(z)
d[y] = d[x]
v.append(y)
sr = set()
sc = set()
del q[:]
for x in v:
r, c = a[x]
for rr in xrange(r - 2, r + 3):
sr.add(rr)
for cc in xrange(c - 2, c + 3):
sc.add(cc)
for i in sr:
for j in row[i].viewvalues():
if d[j] == inf:
d[j] = d[x] + 1
pu(j)
row[i] = {}
for i in sc:
for j in col[i].viewvalues():
if d[j] == inf:
d[j] = d[x] + 1
pu(j)
col[i] = {}
ans = inf
for i in xrange(k):
r, c = a[i]
if r == n and c == m:
if ans > d[i]:
ans = d[i]
if r >= n - 1:
if ans > d[i] + 1:
ans = d[i] + 1
if c >= m - 1:
if ans > d[i] + 1:
ans = d[i] + 1
if ans == inf:
print -1
else:
print ans
main()
| Python | [
"graphs"
] | 1,212 | 2,205 | 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,656 |
d8c2cb03579142f45d46f1fe22a9b8c0 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has n different matryoshkas. Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll — inside the third one and so on. Matryoshka i can be nested inside matryoshka j if out_i \le in_j. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}}), where i_1, i_2, ..., i_k are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index i such that one of the subsets contains the i-th doll, and another subset doesn't.Since the answer can be large, print it modulo 10^9 + 7. | ['dp', 'combinatorics', 'shortest paths', 'sortings', 'data structures', 'binary search'] | from bisect import bisect_left as lb
MOD = 10 ** 9 + 7
n = int(input())
a = [tuple(map(int, input().split())) for _ in range(n)]
a = sorted((in_, out) for out, in_ in a)
dp_suf = [None] * n
for i in range(n - 1, -1, -1):
in_, out = a[i]
j = lb(a, (out, 0))
if j == n:
empty, count = in_, 1
else:
empty, count = dp_suf[j]
empty -= out - in_
if i < n - 1:
if empty > dp_suf[i + 1][0]:
empty, count = dp_suf[i + 1]
elif empty == dp_suf[i + 1][0]:
count += dp_suf[i + 1][1]
dp_suf[i] = empty, count % MOD
print(dp_suf[0][1]) | Python | [
"math",
"graphs"
] | 2,039 | 613 | 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
} | 4,687 |
f00eb0452f5933103f1f77ef06473c6a | Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 \le i \le k). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels?For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly n shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. | ['number theory', 'math'] | for _ in range(int(input())):
n,k=map(int,input().split())
i=2
c=[]
s=int(n**0.5)+1
while i<=k and i<s:
if n%i==0:
c.append(i)
if n//i<=k:
c.append(n//i)
i+=1
if k>=n:
print(1)
elif n%k==0:
print(n//k)
elif len(c)>0:
print(n//max(c))
else:
print(n) | Python | [
"math",
"number theory"
] | 859 | 372 | 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,919 |
b9766f25c8ae179c30521770422ce18b | String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order. | ['greedy', 'strings'] | import sys
from collections import Counter
def io():
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
def main():
s = sys.stdin.readline().strip()
t = sys.stdin.readline().strip()
sc = [0] * 26
tc = [0] * 26
n = len(s)
for i, j in zip(s, t):
sc[ord(i)-ord('A')] += 1
tc[ord(j)-ord('A')] += 1
tf = []
for i in xrange(25, -1, -1):
if sc[i] < tc[i]:
tf.extend([i] * (tc[i] - sc[i]))
print len(tf)
ard = list(s)
sc_ = [0] * 26
for i in xrange(n):
a = ord(s[i]) - ord('A')
sc_[a] += 1
if sc[a] > tc[a]:
if a >= tf[-1] or sc_[a] > tc[a]:
ard[i] = chr(ord('A')+tf.pop())
sc[a] -= 1
sc_[a] -= 1
if not tf: break
sys.stdout.write("".join(ard))
print
io()
main()
| Python | [
"strings"
] | 1,082 | 868 | 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
} | 432 |
378f944b6839376dc71d85059d8efd2f | You have a simple and connected undirected graph consisting of n nodes and m edges.Consider any way to pair some subset of these n nodes such that no node is present in more than one pair. This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \{a,b,c,d\} should have at most 2 edges. Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.Now, do one of the following: Find a simple path consisting of at least \lceil \frac{n}{2} \rceil nodes. Here, a path is called simple if it does not visit any node multiple times. Find a valid pairing in which at least \lceil \frac{n}{2} \rceil nodes are paired. It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement. | ['greedy', 'graphs', 'constructive algorithms', 'dfs and similar', 'trees'] | # Fast IO (only use in integer input)
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
n,m = map(int,input().split())
connectionList = []
for _ in range(n):
connectionList.append([])
for _ in range(m):
u,v = map(int,input().split())
connectionList[u-1].append(v-1)
connectionList[v-1].append(u-1)
DFSLevel = [-1] * n
DFSParent = [-1] * n
vertexStack = []
vertexStack.append((0,1,-1)) # vertex depth and parent
while vertexStack:
vertex,depth,parent = vertexStack.pop()
if DFSLevel[vertex] != -1:
continue
DFSLevel[vertex] = depth
DFSParent[vertex] = parent
for nextV in connectionList[vertex]:
if DFSLevel[nextV] == -1:
vertexStack.append((nextV,depth + 1,vertex))
if max(DFSLevel) >= n//2 + n % 2:
for i in range(n):
if DFSLevel[i] >= (n//2 + n%2):
break
longPath = [str(i + 1)]
while DFSParent[i] != -1:
longPath.append(str(DFSParent[i] + 1))
i = DFSParent[i]
print("PATH")
print(len(longPath))
print(" ".join(longPath))
else:
levelWithVertex = list(enumerate(DFSLevel))
levelWithVertex.sort(key = lambda x: x[1])
i = 0
pair = []
while i < len(levelWithVertex) - 1:
if levelWithVertex[i][1] == levelWithVertex[i + 1][1]:
pair.append([levelWithVertex[i][0],levelWithVertex[i + 1][0]])
i += 2
else:
i += 1
print("PAIRING")
print(len(pair))
for elem in pair:
print(str(elem[0] + 1)+" "+str(elem[1] + 1))
| Python | [
"graphs",
"trees"
] | 1,090 | 1,768 | 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,095 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.