QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#837834#9570. Binary TreeYinyuDreamTL 0ms0kbPython32.3kb2024-12-30 14:44:102024-12-30 14:44:10

Judging History

你现在查看的是最新测评结果

  • [2024-12-30 14:44:10]
  • 评测
  • 测评结果:TL
  • 用时:0ms
  • 内存:0kb
  • [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()

详细

Test #1:

score: 0
Time Limit Exceeded

input:

2
5
0 0
1 5
2 4
0 0
0 0

output:


result: