QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#837834 | #9570. Binary Tree | YinyuDream | TL | 0ms | 0kb | Python3 | 2.3kb | 2024-12-30 14:44:10 | 2024-12-30 14:44:10 |
answer
import sys
def main():
import sys
input = sys.stdin.read
data = input().split()
idx = 0
T = int(data[idx])
idx += 1
for _ in range(T):
n = int(data[idx])
idx += 1
adj = [[] for _ in range(n+1)]
for i in range(1, n+1):
x = int(data[idx])
y = int(data[idx+1])
idx += 2
if x != 0:
adj[i].append(x)
if y != 0:
adj[i].append(y)
size = [0] * (n+1)
def dfs_size(u, p):
size[u] = 1
for v in adj[u]:
if v != p:
dfs_size(v, u)
size[u] += size[v]
dfs_size(1, -1)
def find_centroid(u, p, total):
for v in adj[u]:
if v != p and size[v] > total // 2:
return find_centroid(v, u, total)
return u
current_subtree = set(range(1, n+1))
p_max = int(sys.stdin.readline())
for _ in range(p_max):
temp_adj = [[] for _ in range(n+1)]
for u in current_subtree:
for v in adj[u]:
if v in current_subtree:
temp_adj[u].append(v)
def dfs_temp_size(u, parent):
size[u] = 1
for v in temp_adj[u]:
if v != parent:
dfs_temp_size(v, u)
size[u] += size[v]
dfs_temp_size(next(iter(current_subtree)), -1)
centroid = find_centroid(next(iter(current_subtree)), -1, size[next(iter(current_subtree))])
if len(temp_adj[centroid]) == 0:
other_node = centroid
else:
other_node = temp_adj[centroid][0]
print(f"? {centroid} {other_node}")
sys.stdout.flush()
t = int(sys.stdin.readline())
if t == 0:
current_subtree = {centroid}
elif t == 2:
current_subtree = set(temp_adj[centroid])
elif t == 1:
pass
s = next(iter(current_subtree))
print(f"! {s}")
sys.stdout.flush()
if __name__ == "__main__":
main()
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Time Limit Exceeded
input:
2 5 0 0 1 5 2 4 0 0 0 0