hdu 2544 最短路裸題 SPFA
阿新 • • 發佈:2019-01-06
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <cmath> #include <queue> #include <vector> using namespace std; #define N 100010 #define INF 0x3f3f3f3f int n,m,q; struct Edge{ int next,to,value; }edge[N]; int head[N],tot; bool exist[N]; int dis[N]; queue<int> Q; inline int read() { int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();} return x*f; } void Addedge(int u,int v,int w) { tot++;edge[tot].next=head[u];edge[tot].to=v;edge[tot].value=w;head[u]=tot; tot++;edge[tot].next=head[v];edge[tot].to=u;edge[tot].value=w;head[v]=tot; } void SPFA() { memset(dis,INF,sizeof(dis)); dis[1]=0;exist[1]=1; Q.push(1); while(!Q.empty()) { int now=Q.front();Q.pop(); exist[now]=false; for(int i=head[now];i;i=edge[i].next) { int v=edge[i].to; if(dis[v]>dis[now]+edge[i].value) { dis[v]=dis[now]+edge[i].value; if(!exist[v]) { exist[v]=true; Q.push(v); } } } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { if(n==0&&m==0) break; tot=0; memset(head,0,sizeof(head)); for(int i=1;i<=m;i++) { int x=read(),y=read(),z=read(); Addedge(x,y,z); } SPFA(); cout<<dis[n]<<endl; } return 0; }