結果

問題 No.1212 Second Path
ユーザー lam6er
提出日時 2025-03-26 15:50:31
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 3,700 bytes
コンパイル時間 244 ms
コンパイル使用メモリ 82,240 KB
実行使用メモリ 348,492 KB
最終ジャッジ日時 2025-03-26 15:51:37
合計ジャッジ時間 10,516 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample -- * 3
other TLE * 1 -- * 44
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from sys import stdin
from collections import deque

sys.setrecursionlimit(1 << 25)

def input():
    return sys.stdin.readline()

def main():
    N = int(input())
    edges = [[] for _ in range(N+1)]  # 1-based
    for _ in range(N-1):
        u, v, w = map(int, input().split())
        edges[u].append((v, w))
        edges[v].append((u, w))
    
    # Preprocess for LCA
    LOG = 20
    parent = [[-1]*(N+1) for _ in range(LOG)]
    depth = [0]*(N+1)
    
    # BFS to set up parent[0] and depth
    root = 1
    q = deque()
    q.append(root)
    parent[0][root] = -1
    while q:
        u = q.popleft()
        for v, w in edges[u]:
            if parent[0][v] == -1 and v != root:
                parent[0][v] = u
                depth[v] = depth[u] + 1
                q.append(v)
    
    # Fill parent table
    for k in range(1, LOG):
        for v in range(1, N+1):
            if parent[k-1][v] != -1:
                parent[k][v] = parent[k-1][parent[k-1][v]]
    
    def lca(u, v):
        if depth[u] < depth[v]:
            u, v = v, u
        # Bring u to the same depth as v
        for k in range(LOG-1, -1, -1):
            if depth[u] - (1 << k) >= depth[v]:
                u = parent[k][u]
        if u == v:
            return u
        # Now find LCA
        for k in range(LOG-1, -1, -1):
            if parent[k][u] != -1 and parent[k][u] != parent[k][v]:
                u = parent[k][u]
                v = parent[k][v]
        return parent[0][u]
    
    # Precompute the path from u to ancestor
    def get_path(u, ancestor):
        path = []
        while u != ancestor:
            path.append(u)
            u = parent[0][u]
        path.append(ancestor)
        return path
    
    # Sort adjacency lists by weight
    for u in range(1, N+1):
        edges[u].sort(key=lambda x: x[1])
    
    Q = int(input())
    for _ in range(Q):
        x, y = map(int, input().split())
        if x == y:
            print(0)
            continue
        l = lca(x, y)
        path_x = get_path(x, l)
        path_y = get_path(y, l)
        path = path_x[:-1] + path_y[::-1]
        S = 0
        # Compute S, the shortest path length
        # To compute S, we need to sum the edges along the path
        # Since the path is a list of nodes, need to find the edges between consecutive nodes
        # Precompute edge weights between consecutive nodes in the path
        S = 0
        path_edges = set()  # Store pairs (u, v) and (v, u)
        for i in range(len(path)-1):
            u, v = path[i], path[i+1]
            # Find the edge weight between u and v
            for (adj, w) in edges[u]:
                if adj == v:
                    S += w
                    path_edges.add((u, adj))
                    path_edges.add((adj, u))
                    break
        
        # Now, for each node in the path, find the minimum edge not in the path
        min_extra = float('inf')
        for i in range(len(path)):
            u = path[i]
            prev_node = path[i-1] if i > 0 else None
            next_node = path[i+1] if i < len(path)-1 else None
            # Iterate through sorted edges of u
            for (v, w) in edges[u]:
                # Check if this edge is part of the path
                if (prev_node is not None and v == prev_node) or (next_node is not None and v == next_node):
                    continue
                if w < min_extra:
                    min_extra = w
                break  # Since edges are sorted, first valid is the smallest
        
        if min_extra == float('inf'):
            print(-1)
        else:
            print(S + 2 * min_extra)
    
if __name__ == "__main__":
    main()
0