結果
| 問題 | No.1320 Two Type Min Cost Cycle |
| コンテスト | |
| ユーザー |
norioc
|
| 提出日時 | 2026-08-23 19:05:53 |
| 言語 | PyPy3 (7.3.23) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,141 bytes |
| 記録 | |
| コンパイル時間 | 273 ms |
| コンパイル使用メモリ | 95,848 KB |
| 実行使用メモリ | 92,492 KB |
| 最終ジャッジ日時 | 2026-08-23 19:06:28 |
| 合計ジャッジ時間 | 18,103 ms |
|
ジャッジサーバーID (参考情報) |
judge2_0 / judge1_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 WA * 2 |
| other | AC * 28 WA * 29 |
ソースコード
from collections import defaultdict
from heapq import heappush, heappop
def dijkstra(n: int, sv, adj):
dists = [INF] * n
dists[sv] = 0
q = [(0, sv)]
while q:
d, v = heappop(q)
if dists[v] != d: continue
for to, w in adj[v]:
nd = dists[v] + w
if dists[to] > nd:
dists[to] = nd
heappush(q, (nd, to))
return dists
INF = 1 << 62
T = 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))
def solve_undirected():
res = INF
adj = defaultdict(list)
edge2w = {}
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
edge2w[u, v] = w
used = set()
for i in range(N): # 頂点 i を始点とする最短経路を求める
# if i in used: continue
dists = dijkstra(N, i, adj)
for j in range(N):
if dists[j] == INF: continue
if (j, i) in edge2w:
res = min(res, dists[j] + edge2w[(j, i)])
return res
def solve_directed():
res = INF
adj = defaultdict(list)
edge2w = {}
for u, v, w in edges:
adj[u].append((v, w))
edge2w[u, v] = w
for i in range(N):
# 頂点 i を始点として、各頂点への最小経路を作る
dists = [INF] * N
dists[i] = 0
q = [(0, i)]
while q:
d, v = heappop(q)
if dists[v] != d: continue
for to, w in adj[v]:
nd = dists[v] + w
if dists[to] > nd:
dists[to] = nd
heappush(q, (nd, to))
# 各頂点から始点 i への有向辺があるなら閉路が存在する
for j in range(N):
if dists[j] != INF:
if (j, i) in edge2w:
res = min(res, dists[j] + edge2w[j, i])
if res == INF:
return -1
return res
if T == 0:
ans = solve_undirected()
print(ans)
else:
ans = solve_directed()
print(ans)
norioc