QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#640135 | #2918. Tree Number Generator | enze114514 | RE | 0ms | 0kb | Python3 | 1.9kb | 2024-10-14 07:12:34 | 2024-10-14 07:12:34 |
answer
import sys
import threading
import math
sys.setrecursionlimit(1 << 25)
def main():
n, m, q = map(int, sys.stdin.readline().split())
n += 1 # Adjusting for 1-based indexing
edges = [[] for _ in range(n)]
for _ in range(n - 2):
x, y = map(int, sys.stdin.readline().split())
edges[x].append(y)
edges[y].append(x)
digits = [0] * n
for i in range(1, n):
digits[i] = int(sys.stdin.readline())
LOGN = 20
up = [[0] * LOGN for _ in range(n)]
depth = [0] * n
f = [0] * n
len_u = [0] * n
pow10 = [1] * (n)
for i in range(1, n):
pow10[i] = (pow10[i - 1] * 10) % m
def dfs(u, p):
up[u][0] = p
for k in range(1, LOGN):
up[u][k] = up[up[u][k - 1]][k - 1]
if p == 0:
f[u] = digits[u] % m
len_u[u] = 1
depth[u] = 0
else:
f[u] = (f[p] * 10 + digits[u]) % m
len_u[u] = len_u[p] + 1
depth[u] = depth[p] + 1
for v in edges[u]:
if v != p:
dfs(v, u)
dfs(1, 0)
def lca(u, v):
if depth[u] < depth[v]:
u, v = v, u
for k in range(LOGN - 1, -1, -1):
if depth[u] - (1 << k) >= depth[v]:
u = up[u][k]
if u == v:
return u
for k in range(LOGN - 1, -1, -1):
if up[u][k] != up[v][k]:
u = up[u][k]
v = up[v][k]
return up[u][0]
for _ in range(q):
a, b = map(int, sys.stdin.readline().split())
L = lca(a, b)
len1 = len_u[a]
len2 = len_u[b] - len_u[L]
num1 = f[a]
num2 = (f[b] - f[L] * pow10[len_u[b] - len_u[L]] % m + m) % m
result = (num1 * pow10[len2] + num2) % m
print(result)
threading.Thread(target=main).start()
详细
Test #1:
score: 0
Dangerous Syscalls
input:
2 1 4 1 2 1 3 1 2 2 1 1 1 2 2