結果

問題 No.1320 Two Type Min Cost Cycle
ユーザー 草苺奶昔
提出日時 2023-04-02 19:16:48
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 822 ms / 2,000 ms
コード長 2,369 bytes
コンパイル時間 185 ms
コンパイル使用メモリ 82,376 KB
実行使用メモリ 84,016 KB
最終ジャッジ日時 2024-09-25 00:36:29
合計ジャッジ時間 14,846 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 57
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
from heapq import heappop, heappush
from typing import List, Tuple

INF = int(1e18)


def minCostCycle(n: int, edges: List[Tuple[int, int, int]], directed: bool) -> int:
    adjList = [[] for _ in range(n)]
    maxWeight = 0
    for u, v, w in edges:
        if w > maxWeight:
            maxWeight = w
        adjList[u].append((v, w))
        if not directed:
            adjList[v].append((u, w))
    res = INF
    for i in range(len(edges)):  # remove edge i
        from_, to, weight = edges[i]
        dist = _bfs01(adjList, to, from_) if maxWeight <= 1 else _dijkstra(adjList, to, from_)
        cand = weight + dist
        if cand < res:
            res = cand
    return res


def _bfs01(adjList: List[List[Tuple[int, int]]], start: int, target: int) -> int:
    n = len(adjList)
    dist = [INF] * n
    dist[start] = 0
    queue = deque([start])
    while queue:
        cur = queue.popleft()
        if cur == target:
            return dist[cur]
        for next, weight in adjList[cur]:
            if (cur, next) == (start, target) or (cur, next) == (target, start):
                continue
            cand = dist[cur] + weight
            if cand < dist[next]:
                dist[next] = cand
                if weight == 0:
                    queue.appendleft(next)
                else:
                    queue.append(next)
    return INF


def _dijkstra(adjList: List[List[Tuple[int, int]]], start: int, target: int) -> int:
    n = len(adjList)
    dist = [INF] * n
    dist[start] = 0
    pq = [(0, start)]
    while pq:
        curDist, cur = heappop(pq)
        if cur == target:
            return curDist
        if dist[cur] < curDist:
            continue
        for next, weight in adjList[cur]:
            if (cur, next) == (start, target) or (cur, next) == (target, start):
                continue
            cand = curDist + weight
            if cand < dist[next]:
                dist[next] = cand
                heappush(pq, (cand, next))
    return INF


if __name__ == "__main__":
    directed = int(input())
    n, m = map(int, input().split())
    edges = []
    for _ in range(m):
        u, v, w = map(int, input().split())
        u -= 1
        v -= 1
        edges.append((u, v, w))
    res = minCostCycle(n, edges, directed == 1)
    if res == INF:
        res = -1
    print(res)
0