結果
| 問題 | No.1320 Two Type Min Cost Cycle |
| コンテスト | |
| ユーザー |
norioc
|
| 提出日時 | 2026-08-23 19:38:34 |
| 言語 | PyPy3 (7.3.23) |
| 結果 |
AC
|
| 実行時間 | 1,489 ms / 2,000 ms |
| + 937µs | |
| コード長 | 2,695 bytes |
| 記録 | |
| コンパイル時間 | 239 ms |
| コンパイル使用メモリ | 95,852 KB |
| 実行使用メモリ | 108,660 KB |
| 最終ジャッジ日時 | 2026-08-23 19:38:53 |
| 合計ジャッジ時間 | 18,696 ms |
|
ジャッジサーバーID (参考情報) |
judge3_0 / judge2_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 57 |
ソースコード
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 << 60
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)
for i, (u, v, w) in enumerate(edges):
adj[u].append((v, w, i))
adj[v].append((u, w, i))
for i in range(N): # 頂点 i を始点とする最短経路を求める
dists = [INF] * N
dists[i] = 0
# q = [(0, i, -1)]
q = [(i, -1)]
edge_used = set()
while q:
# d, v, ei = heappop(q)
x, ei = heappop(q)
d = x // 10000
v = x % 10000
if dists[v] != d: continue
if ei != -1:
edge_used.add(ei)
for to, w, i in adj[v]:
nd = dists[v] + w
if dists[to] > nd:
dists[to] = nd
# heappush(q, (nd, to, i))
x = nd * 10000 + to
heappush(q, (x, i))
for j, (u, v, w) in enumerate(edges):
if j in edge_used: continue
d = dists[u] + dists[v] + w
res = min(res, d)
if res == INF:
return -1
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