結果

問題 No.1833 Subway Planning
ユーザー LyricalMaestro
提出日時 2025-05-10 20:48:36
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 2,168 bytes
コンパイル時間 462 ms
コンパイル使用メモリ 82,416 KB
実行使用メモリ 356,708 KB
最終ジャッジ日時 2025-05-10 20:48:49
合計ジャッジ時間 12,387 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample -- * 3
other AC * 4 WA * 2 TLE * 1 -- * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

## https://yukicoder.me/problems/no/1833

from collections import deque

def solve(N, next_nodes, border):
    start_v = -1
    for i in range(N):
        for b, c in next_nodes[i]:
            if c > border:
                start_v = i
                break
        if start_v != -1:
            break
    if start_v == -1:
        return True

    # 最小シュタイナー木を求めていく
    stack = deque()
    stack.append((start_v, 0))
    has_needs = [False] * N
    parents = [-2] * N
    parents[start_v] = -1
    edges = []
    while len(stack) > 0:
        v, index = stack.pop()
        if index > 0:
            w, c = next_nodes[v][index - 1]
            if has_needs[w] and not has_needs[v]:
                has_needs[v] = True
                if c <= border:
                    edges.append((v, w, c))

        while index < len(next_nodes[v]):
            w, c = next_nodes[v][index]
            if w == parents[v]:
                index += 1
                continue
            
            if c > border:
                edges.append((v, w, c))
                has_needs[w] = True
            parents[w] = v
            stack.append((v, index + 1))
            stack.append((w, 0))
            break

    in_degrees = [0] * N
    min_c = float("inf")
    for u, v, c in edges:
        in_degrees[u] += 1
        in_degrees[v] += 1
        min_c = min(min_c, c)
    for j in range(N):
        if in_degrees[j] > 2:
            return False
    edges.sort(key=lambda x : x[2])
    return edges[-1][2] - min_c <= border
    
    




    



def main():
    N = int(input())
    max_c = 0
    next_nodes = [[] for _ in range(N)]
    for _ in range(N - 1):
        a, b, c = map(int, input().split())
        next_nodes[a - 1].append((b - 1, c))
        next_nodes[b - 1].append((a - 1, c))
        max_c = max(max_c, c)
    
    low = 0
    high = max_c
    while high - low > 1:
        mid = (high + low) // 2
        if solve(N, next_nodes, mid):
            high = mid
        else:
            low = mid
    if solve(N, next_nodes, low):
        print(low)
    else:
        print(high)

    








if __name__ == '__main__':
    main()
0