3 4 4 1 2 5 2 4 10 1 3 3 3 4 8 3 2 1 2 5 2 3 10 2 2 1 2 1 1 2 2
15 -1 2
#include<stdio.h>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 1005;
const int inf = 999999999;
struct EDG
{
int v,d,id;
};
vector<EDG>mapt[N];
bool inq[N];
int dis[N],frome[N],id[N],n;
void init()
{
for(int i=0;i<=n;i++)
{
mapt[i].clear(); id[i]=inf; frome[i]=i;
}
}
inline void spfa(int a,bool recode)
{
queue<int>q;
int s;
for(int i=1;i<=n;i++)
dis[i]=inf,inq[i]=false;
inq[n]=true;
dis[1]=0; q.push(1);
while(!q.empty())
{
s=q.front(); q.pop();
inq[s]=false;
for(int i=0;i<mapt[s].size();i++)
if(id[a]!=mapt[s][i].id||recode)
{
int now=mapt[s][i].v;
if(dis[now]>dis[s]+mapt[s][i].d)
{
dis[now]=dis[s]+mapt[s][i].d;
if(recode)
frome[now]=s,id[now]=mapt[s][i].id;
if(!inq[now])
inq[now]=true,q.push(now);
}
}
}
}
int main()
{
int m,a,b,ans,t;
EDG edg;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
init();
while(m--)
{
scanf("%d%d%d",&a,&b,&edg.d);
edg.id=m;
edg.v=b; mapt[a].push_back(edg);
edg.v=a; mapt[b].push_back(edg);
}
if(n==1)
{
printf("0\n");continue;
}
spfa(0,true);
ans=-1;
a=n;
while(frome[a]!=a)
{
b=frome[a];
spfa(a,false);
if(dis[n]>ans&&dis[n]!=inf)
ans=dis[n];
else if(dis[n]==inf)
{
ans=-1; break;
}
a=b;
}
printf("%d\n",ans);
}
}
HDU3986Harry Potter and the Final Battle(SPFA册边)
原文地址:http://blog.csdn.net/u010372095/article/details/45013717