题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=66569#problem/K
题意:给出一个约束差分系统,求最短路,现在才明白什么叫差分约束系统。。。。
不知道为什么栈模拟能够AC,而队列模拟却不能?也许这要看出题人给出的数据了,如果出题人要故意卡队列版SPFA,那又有什么办法呢。
如果用栈模拟+vector,还是TLE,然后换成栈模拟+前向星就过了,看来前向星还是不错的嘛,而且代码量感觉和用vector来写差不多,以后就慢慢用栈模拟+前向星来写最短路吧。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF 0x7fffffff
using namespace std;
struct edge{
int front,to,w;
}E[150010];
int last[30010],dis[30010],vis[30010];
int N,M,S[30010],top;
void SPFA(){
memset(vis,0,sizeof(vis));
for(int i=0;i<=N;i++) dis[i]=INF;
top=0;S[top++]=1;
vis[1]=1;dis[1]=0;
while(top){//栈模拟SPFA
int tp=S[--top];vis[tp]=0;
for(int p=last[tp];p>=0;p=E[p].front){
int u=tp,v=E[p].to,w=E[p].w;
if(dis[u]+w>=dis[v]) continue;
dis[v]=dis[u]+w;
if(!vis[v]) vis[v]=1,S[top++]=v;
}
}
}
int main(){
//freopen("D:in.txt","r",stdin);
while(cin>>N){
cin>>M;
memset(last,-1,sizeof(last));//初始化
int a,b,c;
for(int i=0;i<M;i++){//用前向星存储边集
scanf("%d %d %d",&a,&b,&c);
E[i]=(edge){last[a],b,c};
last[a]=i;
}
SPFA();
cout<<dis[N]<<endl;
}
return 0;
}