N 個路口(N ≤ 100),M 條雙向路(M ≤ 10000)。1 號商店到 N 號賽場最短時間。邊權為正。
將無向邊拆為兩條有向邊。
dis[1] = 0,其餘 INF。
重複 N-1 輪松弛所有邊:
if (dis[v] > dis[u] + w) dis[v] = dis[u] + w。
若某輪無更新則提前結束。
#include <bits/stdc++.h>
using namespace std;
const int MAXV = 110;
const int MAXE = 20020;
const int INF = 1e9;
struct Edge { int from, to, cost; } edges[MAXE];
int dis[MAXV];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int V, E;
while (cin >> V >> E, V || E) {
int ecnt = 0;
for (int i = 0; i < E; i++) {
int a, b, c; cin >> a >> b >> c;
edges[ecnt++] = {a, b, c};
edges[ecnt++] = {b, a, c}; // 無向拆雙向
}
fill(dis, dis + V + 1, INF);
dis[1] = 0;
while (true) {
bool updated = false;
for (int i = 0; i < ecnt; i++) {
int u = edges[i].from, v = edges[i].to, w = edges[i].cost;
if (dis[u] != INF && dis[u] + w < dis[v]) {
dis[v] = dis[u] + w;
updated = true;
}
}
if (!updated) break;
}
cout << dis[V] << '\n';
}
return 0;
}