HDU 1874
HDU 1874
Dijkstra
注意初始化
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
const int N = 1e3 + 10,INF = 0x3f3f3f3f;
int n,m,dist[N],g[N][N];
bool st[N];
void dij(int x) {
memset(dist,0x3f,sizeof dist);
memset(st,0,sizeof st);
dist[x] = 0;
for(int i = 0;i < n; ++i) {
int t = -1;
for(int j = 0;j < n; ++j) {
if(!st[j] && (t == -1 || dist[t] > dist[j])) t = j;
}
st[t] = 1;
for(int j = 0;j < n; ++j) {
dist[j] = min(dist[j],dist[t] + g[t][j]);
}
}
}
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
while(cin >> n >> m) {
int a,b,c,starti,endi;
memset(g,0x3f,sizeof g);
for(int i = 0;i < m; ++i) {
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b],c);
}
cin >> starti >> endi;
dij(starti);
if(dist[endi] == INF) cout << "-1";
else cout << dist[endi];
cout << endl;
}
return 0;
}