SPFA 求最短路
附代码(AC,270MS)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int MAX = 1e3 + 5;
const int INF = 0x7fffff;
int n, m;
int disa[MAX], disb[MAX];
struct edge_{
int t, v;
}tp;
vector<edge_> amap[MAX];
void init(){
for(int i = 0; i < MAX; ++i){
disa[i] = INF;
disb[i] = INF;
amap[i].clear();
}
}
void spfa(int s, int *dis){
int now, size, to;
queue<int> tag;
tag.push(s);
dis[s] = 0;
while(!tag.empty()){
now = tag.front();
tag.pop();
size = amap[now].size();
for(int i = 0; i < size; ++i){
to = amap[now][i].t;
if(dis[to] > dis[now] + amap[now][i].v){
dis[to] = dis[now] + amap[now][i].v;
tag.push(to);
}
}
}
}
int main(){
int a, b, v;
while(~scanf("%d%d", &n, &m)){
init();
while(m--){
scanf("%d%d%d", &a, &b, &v);
tp.t = b, tp.v = v;
amap[a].push_back(tp);
tp.t = a;
amap[b].push_back(tp);
}
spfa(1, disa);
spfa(n, disb);
int ans = INF;
for(int i = 1; i <= n; ++i){
if(ans > disa[i] + disb[i])
ans = disa[i] + disb[i];
}
if(ans >= INF)
printf("-1\n");
else
printf("%d\n", ans);
}
return 0;
}