又是一个简单的差分约束
第一次发现spfa不仅可以用队列,还可以用栈,感觉好神奇
顺便存一下代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
const int maxn = 31234;
const int maxm = 151234;
struct Edge{
int next;
int to;
int v;
Edge(){}
Edge(int next,int to,int v):next(next),to(to),v(v){}
};
Edge edge[maxm];
int head[maxn],top;
void init(int n){
memset(head,-1,sizeof(head));
top = 0;
}
void Link(int st,int ed,int v){
edge[top] = Edge(head[st],ed,v);
head[st] = top++;
}
bool vis[maxn];
int dis[maxn];
stack<int> Q;
int spfa(int st,int end){
while(Q.empty()==false){
Q.pop();
}
memset(dis,0x3f,sizeof(dis));
dis[st] = 0;
vis[st] = true;
Q.push(st);
while(Q.empty()==false){
st = Q.top();
vis[st] = false;
Q.pop();
for(int i = head[st];~i;i = edge[i].next){
int ed = edge[i].to;
int v = edge[i].v;
if(dis[ed] > dis[st] + v){
dis[ed] = dis[st] + v;
if(vis[ed] == false){
Q.push(ed);
vis[ed] = true;
}
}
}
}
return dis[end];
}
int main(){
int n,m;
while(~scanf("%d %d",&n,&m)){
init(n);
int x,y,v;
while(m--){
scanf("%d %d %d",&x,&y,&v);
Link(x,y,v);
}
printf("%d\n",spfa(1,n));
}
return 0;
}