BSUIR Open X. Reload. Students final

· · 个人记录

link

你说得对,但是为啥比赛时长 10\text{min} 啊?

A. Stickers for BSUIR Open

二分答案 x,只需比较 \left\lfloor\dfrac nx\right\rfloor\left\lfloor\dfrac mx\right\rfloor 与 k 的大小即可。

n, m, k = map(int, input().split())

l, r = 0, min(n, m)
while r - l > 1e-8:
    mid = (l + r) / 2
    if int(n / mid) * int(m / mid) >= k: l = mid
    else: r = mid

print((l + r) / 2)

B. Two trees

考率把原图分成一棵树和森林,那么构造染色方案是容易的。

观察到「边集无环」是拟阵,「删去该边集仍联通」也是拟阵,求一个拟阵交即可,答案即为分出的森林。注意判掉剩下的不是树的情况,此时无解。复杂度 O(n^3)。

from collections import deque

class DSU:
    def __init__(self, n):
        self.f, self.sz, self.cnt = list(range(n)), [1] * n, n
    def fa(self, x):
        if x != self.f[x]: self.f[x] = self.fa(self.f[x])
        return self.f[x]
    def merge(self, u, v):
        u, v = self.fa(u), self.fa(v)
        if u == v: return False
        if self.sz[u] < self.sz[v]: u, v = v, u
        self.f[v] = u; self.sz[u] += self.sz[v]; self.cnt -= 1
        return True

n, m = map(int, input().split())
e = []
for _ in range(m):
    u, v = map(int, input().split())
    e.append((u - 1, v - 1))

ans, sna = [], list(range(m))
while True:
    q, pre = deque(), [-1] * m

    dsu = DSU(n)
    for u in ans: dsu.merge(*e[u])
    for u in sna:
        if dsu.fa(e[u][0]) != dsu.fa(e[u][1]): q.append(u); pre[u] = m

    while q:
        u = q.popleft()
        if u in ans:
            dsu = DSU(n)
            for v in ans:
                if u != v: dsu.merge(*e[v])
            for v in sna:
                if dsu.fa(e[v][0]) != dsu.fa(e[v][1]):
                    if pre[v] == -1: q.append(v); pre[v] = u
        else:
            dsu = DSU(n)
            for v in sna:
                if u != v: dsu.merge(*e[v])
            if dsu.cnt == 1:
                while u != m:
                    if u in ans: ans.remove(u); sna.append(u)
                    else: sna.remove(u); ans.append(u)
                    u = pre[u]
                break
            elif dsu.cnt == 2:
                for v in ans:
                    if dsu.fa(e[v][0]) != dsu.fa(e[v][1]):
                        if pre[v] == -1: q.append(v); pre[v] = u
    else: break

dsu = DSU(n)
for i in sna:
    if not dsu.merge(*e[i]):
        print('No')
        exit()

dsu, col = DSU(n), [1] * m
for i in ans: dsu.merge(*e[i])
for i in sna: col[i] = 3 if dsu.merge(*e[i]) else 2
print('Yes')
print(*col)

C. Sum of fractions

固定 k,那么解的个数为满足 a\le b,(a+b)k\bmod ab=0 的 (a,b) 个数,设 \gcd(a,b)=g,a=a'g,b=b'g,则有 (a'+b')k\bmod a'b'g=0,那么 k\bmod a'b'=0。于是解的个数为 \displaystyle\sum_{a'b'|k,\gcd(a',b')=1}\llap{}d\left(\dfrac{k(a'+b')}{a'b'}\right)。

人类智慧的,解的个数很多时,k 必然有较多因数,因此 k 不会包含较大的质因数。具体的,r=10^9 时 k 最大的质因子只有 19,同时每个质因子的次幂不超过上一个 +1。同时对于答案不是前缀 \max 的不再拓展状态,此时有效的 k 只剩几百个。于是可以直接爆搜并加上一些其它强力剪枝,可以在几秒内跑出来。

以下 \text{python} 代码在 r=10^9 时大约需要 1.5\text s,翻译成 \text{C++} 后只需 0.2\sim0.3\text s,可供参考。

r = int(input())

N = 1 << 20
p, d, c = [], [0] * (N + 1), [0] * (N + 1)
d[1] = 1
for i in range(2, N + 1):
    if d[i] == 0: d[i], c[i] = 2, 1; p.append(i)
    for j in p:
        if i * j > N: break
        if i % j != 0: d[i * j], c[i * j] = d[i] * 2, 1
        else: d[i * j], c[i * j] = d[i] // (c[i] + 1) * (c[i] + 2), c[i] + 1; break

def calc(x):
    if x <= N: return d[x]
    res = 1
    for i in p:
        if i * i > x: break
        c = 0
        while x % i == 0: x //= i; c += 1
        res *= c + 1
        if x <= N: return res * d[x]
    return res * 2

ck, ks = [0] * 8, []
def dfsk(u, k):
    if u == 8:
        if k != 1: ks.append((k, ck[:]))
        return
    ck[u] = 0
    while k <= r and (u == 0 or ck[u] <= ck[u - 1] + 1):
        dfsk(u + 1, k)
        k *= p[u]; ck[u] += 1
dfsk(0, 1)
ks.sort(key = lambda x: x[0])

k, ca = 0, [0] * 8
res, ans, mn = 0, 2, 1

def dfsb(u, b, a):
    if u == 8:
        global res
        res += calc(k // (a * b) * (a + b))
        return
    if ca[u]: dfsb(u + 1, b, a)
    else:
        c = 0
        while b <= a and c <= ck[u]:
            dfsb(u + 1, b, a)
            b *= p[u]; c += 1
def dfsa(u, a):
    if u == 8:
        dfsb(0, 1, a)
        return
    ca[u] = 0
    while ca[u] <= ck[u]:
        dfsa(u + 1, a)
        a *= p[u]; ca[u] += 1

ok = set(p[:8])
for k_, ck_ in ks:
    if k_ in ok:
        k, ck, res = k_, ck_, 0
        dfsa(0, 1)
        if res > ans:
            ans, mn = res, k
            for i in p[:8]: ok.add(k * i)

print(mn, ans)

D. Binary tree

观察到 \text{rotate} 操作不会改变中序遍历的结果,于是相当于先把原树的中序遍历拿出来,然后用最少的 \text{swap} 操作排序。显然选择排序是最优的,只会 \text{swap} O(n) 次。

考虑如何 \text{swap} 两个数,只需把它们 \text{rotate} 到根,使得它们相邻,然后就能换了。可以使用类似 \text{Splay} 的旋转方法,这样均摊是一次 O(\log n) 的,总次数 O(n\log n)。

__import__('sys').setrecursionlimit(10 ** 4)

n = int(input())
idx, val, lc, rc, fa = {}, [0] * n, [0] * n, [0] * n, [-1] * n
for i in range(n):
    v, l, r = map(int, input().split())
    l -= 1; r -= 1
    idx[v], val[i], lc[i], rc[i] = i, v, l, r
    if l != -1: fa[l] = i
    if r != -1: fa[r] = i

a = []
def dfs(u):
    if lc[u] != -1: dfs(lc[u])
    a.append(val[u])
    if rc[u] != -1: dfs(rc[u])
for i in range(n):
    if fa[i] == -1: dfs(i)
pos, b = {x: i for i, x in enumerate(a)}, sorted(a)

ans = []

def rotate(u):
    f = fa[u]
    ans.append(('rotate', u))
    if fa[f] != -1:
        if lc[fa[f]] == f: lc[fa[f]] = u
        else: rc[fa[f]] = u
    if lc[f] == u:
        if rc[u] != -1: fa[rc[u]] = f
        lc[f], rc[u], fa[u], fa[f] = rc[u], f, fa[f], u
    else:
        if lc[u] != -1: fa[lc[u]] = f
        rc[f], lc[u], fa[u], fa[f] = lc[u], f, fa[f], u

def rotate_rt(x, e = -1):
    while fa[x] != e:
        if fa[fa[x]] != e:
            if (lc[fa[x]] == x) ^ (lc[fa[fa[x]]] == fa[x]): rotate(x)
            else: rotate(fa[x])
        rotate(x)

for i in range(n):
    if a[i] != b[i]:
        rotate_rt(idx[a[i]])
        rotate_rt(idx[b[i]], idx[a[i]])
        ans.append(('swap', idx[b[i]]))
        idx[a[i]], idx[b[i]] = idx[b[i]], idx[a[i]]
        p = pos[b[i]]
        pos[a[i]], pos[b[i]] = pos[b[i]], pos[a[i]]
        a[i], a[p] = a[p], a[i]

print(len(ans))
print('\n'.join(f'{op} {u + 1}' for op, u in ans))

E. Kitten rescue

状态数只有 O(n^2m^2) 个,直接搜即可。

n, m = map(int, input().split())
a = [input() for _ in range(n)]

def dis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def get(x1, y1, x2, y2):
    if y1 - 1 == y2: return 'L'
    if y1 + 1 == y2: return 'R'
    if x1 - 1 == x2: return 'U'
    if x1 + 1 == x2: return 'D'

flag, sdx, sdy = False, 0, 0
for i in range(n):
    for j in range(m):
        if a[i][j] == 'C':
            scx, scy = i, j
        elif a[i][j] == '@':
            sdx, sdy = i, j
            flag = True

pre = [[[[None] * m for _ in range(n)] for _ in range(m)] for _ in range(n)]
q = __import__('collections').deque()

pre[scx][scy][sdx][sdy] = (-1, -1, -1, -1)
q.append((scx, scy, sdx, sdy))

while q:
    cx, cy, dx, dy = q.popleft()
    for ncx, ncy in ((cx, cy - 1), (cx, cy + 1), (cx - 1, cy), (cx + 1, cy)):
        if 0 <= ncx < n and 0 <= ncy < m and a[ncx][ncy] != '#' and (not flag or ncx != dx or ncy != dy):
            if a[ncx][ncy] == 'K':
                ans = [get(cx, cy, ncx, ncy)]
                while pre[cx][cy][dx][dy] != (-1, -1, -1, -1):
                    ans.append(get(pre[cx][cy][dx][dy][0], pre[cx][cy][dx][dy][1], cx, cy))
                    cx, cy, dx, dy = pre[cx][cy][dx][dy]
                print('Yes')
                print(''.join(reversed(ans)))
                exit()
            ndx, ndy = dx, dy
            if flag:
                for _ in range(2):
                    mn = (dis(ncx, ncy, ndx, ndy), -1, ndx, ndy)
                    for odx, ody, dd in ((ndx, ndy - 1, 0), (ndx, ndy + 1, 0), (ndx - 1, ndy, 1), (ndx + 1, ndy, 1)):
                        if 0 <= odx < n and 0 <= ody < m and a[odx][ody] != '#':
                            mn = min(mn, (dis(ncx, ncy, odx, ody), dd, odx, ody))
                    ndx, ndy = mn[2], mn[3]
            if pre[ncx][ncy][ndx][ndy] is None and (not flag or ncx != ndx or ncy != ndy):
                pre[ncx][ncy][ndx][ndy] = (cx, cy, dx, dy)
                q.append((ncx, ncy, ndx, ndy))

print('No')

G. Borrow checker

小模拟,直接做就好了。

func = {}

for _ in range(int(input())):
    qwq, awa = input().split('(')
    name = qwq[4:] if qwq[3] == '&' else qwq[3:]
    args = [] if awa == ')' else [1 if i[0] == '&' else 0 for i in awa[:-1].split(', ')]
    ret = 1 if qwq[3] == '&' else 0
    func[name] = (args, ret)

line = 0

def err():
    print('Error in line', line)
    exit()

cnt, var, ok, cur = 0, {}, set(), set()

def new():
    global cnt
    ok.add(cnt := cnt + 1)
    return cnt

def get(expr):
    name = expr[1:] if expr[0] == '&' else expr
    if name not in var: err()
    if var[name][1] not in ok: err()
    if var[name][0] == 0:
        if expr[0] == '&':
            cur.add(var[name][1])
            return 1, var[name][1]
        if var[name][1] in cur: err()
        ok.discard(var[name][1])
        return 0, var[name][1]
    else:
        if expr[0] == '&': err()
        cur.add(var[name][1])
        return 1, var[name][1]

def calc(expr):
    if expr[-1] == ')':
        fname, qwq = expr.split('(', 1)
        if fname not in func: err()
        args, dep, arg = [], 0, ''
        for c in qwq[:-1]:
            if c == '(': dep += 1
            elif c == ')': dep -= 1
            if c == ',' and dep == 0: args.append(arg); arg = ''
            elif c != ' ': arg += c
        if arg: args.append(arg)
        if [calc(i)[0] for i in args] != func[fname][0]: err()
        return func[fname][1], new()
    else:
        res = get(expr)
        return (0, new()) if res[0] == 0 else res

for _ in range(int(input())):
    line, cur = line + 1, set()
    name, expr = input().split(' := ')
    value = calc(expr)
    if name in var and var[name][0] == 0: ok.discard(var[name][1])
    var[name] = value

print('Valid')

H. Birthday

手玩可以发现,若 2\mid n 则答案为 \dfrac n2,否则答案为 n-3。

注意特判 n=4。

n = int(input())

if n & 1: print(n - 3)
elif n == 4: print(1)
else: print(n // 2)

I. Palindrome tree

由于让答案字典序最小,因此 1 必然在答案内,然后依次加入 2\sim n,能加就加。

考虑如何 chk:设当前枚举到 i,答案集合为 S,则把 i 到 S 的路径拎出来,记为 i=p_1,p_2,\cdots,p_l。那么逐个 chk 以 p_j 为一端是否满足不存在长度 >k 的回文串,可以直接哈希等方法。若加入 p_j 后寄了,那么 p_{1\sim j} 都不可能成为答案了,直接打上标记即可。

容易证明一个点只会被 chk 一次,因此复杂度 O(n^2)。

__import__('sys').setrecursionlimit(10 ** 5)

n, k = map(int, input().split())
s = input()
g = [[] for _ in range(n)]
for _ in range(n - 1):
    u, v = map(int, input().split())
    u -= 1; v -= 1
    g[u].append(v); g[v].append(u)

fa = [0] * n
def dfs(u, f = -1):
    fa[u] = f
    for v in g[u]:
        if v != f: dfs(v, u)
dfs(0)

mod = 10 ** 9 + 7
base = __import__('random').randint(100, mod - 100)
pw = [1]
for i in range(n): pw.append(pw[-1] * base % mod)

ans = [i == 0 for i in range(n)]
ban = [False] * n
cur = [0] * n
timer = 0

def dfs2(u, f = -1, h1 = 0, h2 = 0, dep = 0):
    h1 = (h1 * base + ord(s[u])) % mod
    h2 = (h2 + ord(s[u]) * pw[dep]) % mod
    dep += 1
    if dep > k and h1 == h2: return False
    for v in g[u]:
        if v != f and (ans[v] or cur[v] == timer) and not dfs2(v, u, h1, h2, dep): return False
    return True

for i in range(1, n):
    u = i; timer += 1
    while not ans[u]:
        cur[u] = timer
        u = fa[u]
    u = i
    while not ans[u]:
        if ban[u] or not dfs2(u):
            v = i
            while True:
                ban[v] = True
                if v == u: break
                v = fa[v]
            break
        cur[u] = 0
        u = fa[u]
    else:
        u = i
        while not ans[u]:
            ans[u] = True
            u = fa[u]

print(sum(ans))
print(*(i + 1 for i in range(n) if ans[i]))

J. Interdimensional Traveler

设 P_i 为第 i 维坐标 -1 的概率,那么有:P_i=p_iP_i^2+1-p_i。

解方程并舍去不合法的根,可以得到:P_i=\begin{cases}1&0\le p_i\le\dfrac12\\\dfrac{1-p_i}{p_i}&\dfrac12<p_i\le1\end{cases}。

显然每维独立,答案为 \prod P_i^{a_i}。

mod = 1000000007

n = int(input())
a = list(map(int, input().split()))
ans = 1
for i in range(n):
    s, t = map(int, input().split())
    if 2 * s > t: ans = ans * pow(t * pow(s, mod - 2, mod) - 1, a[i], mod) % mod
print(ans)