結果
問題 |
No.1212 Second Path
|
ユーザー |
![]() |
提出日時 | 2025-06-12 16:32:27 |
言語 | PyPy3 (7.3.15) |
結果 |
TLE
|
実行時間 | - |
コード長 | 3,042 bytes |
コンパイル時間 | 321 ms |
コンパイル使用メモリ | 81,832 KB |
実行使用メモリ | 393,976 KB |
最終ジャッジ日時 | 2025-06-12 16:33:14 |
合計ジャッジ時間 | 10,686 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | -- * 3 |
other | TLE * 1 -- * 44 |
ソースコード
import sys from collections import defaultdict, deque def main(): sys.setrecursionlimit(1 << 25) input = sys.stdin.read().split() ptr = 0 N = int(input[ptr]) ptr += 1 edges = [] adj = defaultdict(list) for _ in range(N-1): u = int(input[ptr]) v = int(input[ptr+1]) w = int(input[ptr+2]) ptr +=3 edges.append((u, v, w)) adj[u].append((v, w)) adj[v].append((u, w)) for u in adj: adj[u].sort(key=lambda x: x[1]) LOG = 20 parent = [[-1]*(N+1) for _ in range(LOG)] depth = [0]*(N+1) dist_root = [0]*(N+1) root = 1 stack = [(root, -1, 0, 0)] while stack: u, p, d, cost = stack.pop() parent[0][u] = p depth[u] = d dist_root[u] = cost for v, w in adj[u]: if v != p: stack.append((v, u, d+1, cost + w)) 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 for k in range(LOG-1, -1, -1): if depth[u] - (1 << k) >= depth[v]: u = parent[k][u] if u == v: return u 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] def get_path(u, lca_node): path = [] while u != lca_node: for v, w in adj[u]: if v == parent[0][u]: path.append((u, v, w)) u = v break return path def get_path_edges(u, v): ancestor = lca(u, v) path_u = get_path(u, ancestor) path_v = get_path(v, ancestor) return path_u + path_v[::-1] Q = int(input[ptr]) ptr +=1 for _ in range(Q): x = int(input[ptr]) y = int(input[ptr+1]) ptr +=2 if x == y: print(0) continue path_edges = get_path_edges(x, y) edge_set = set() for u, v, w in path_edges: if u < v: edge_set.add((u, v)) else: edge_set.add((v, u)) sum_s = sum(w for u, v, w in path_edges) min_detour = None path_nodes = set() for u, v, _ in path_edges: path_nodes.add(u) path_nodes.add(v) for u in path_nodes: for v, w in adj[u]: edge_tuple = (u, v) if u < v else (v, u) if edge_tuple not in edge_set: if min_detour is None or w < min_detour: min_detour = w break # since edges are sorted, first non-path edge is minimal if min_detour is not None: print(sum_s + 2 * min_detour) else: print(-1) if __name__ == '__main__': main()