hdu1874畅通工程再续
抠了一天的最短路问题,那个spfa还真是难写,只能照着模板打一遍,还有那个松弛操作有点明白怎么回事,但还是不太清晰,容我再抠抠,然后再用dijksta算法敲一遍这道题吧!
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
int n,m;
const int inf = 0x3f3f3f3f;
int v[2010],next[2010],w[2010];
int first[210],d[210],inq[210],e;
using namespace std;
void init()
{
e = 0;
memset(first,-1,sizeof(first));
}
void add_edge(int a,int b,int c)
{
v[e] = b;
next[e] = first[a];
w[e]= c;
first[a] = e++;
}
void spfa(int src){
queue<int> q;
memset(d,0x3f,sizeof(d));
d[src] = 0,inq[src] = 1;
q.push(src);
while(!q.empty()){
int u = q.front();
q.pop();
inq[u] = 0;
for(int i = first[u];i != -1;i = next[i]){
if(d[v[i]] > d[u]+w[i]){
d[v[i]] = d[u]+w[i];
if(!inq[v[i]]) q.push(v[i]),inq[v[i]] = 1;
}
}
}
}
int main()
{
while(cin >> n>>m)
{
init();
for(int i =0;i < m;i++)
{
int a,b,c;
cin >> a>> b>> c;
add_edge(a,b,c);
add_edge(b,a,c);
}
int x,y;
cin >> x>> y;
spfa(x);
if(d[y] != inf)cout<< d[y]<< endl;
else cout<< "-1"<< endl;
}
return 0;
}

浙公网安备 33010602011771号