1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include<bits/stdc++.h> #define INIT(a,b) memset(a,b,sizeof(a)) #define LL long long using namespace std; const int inf=0x3f3f3f3f; const int maxn=1e4+7; const int mod=1e9+7; struct Edge{ int to,w,next; }e[maxn<<1]; struct Node{ int v,w; bool operator < (const Node &e)const {return w>e.w;} }; int tot=0,Begin[maxn],dis[maxn],n,m; void Add(int x,int y,int w){ e[tot]=(Edge){y,w,Begin[x]}; Begin[x]=tot++; } void Dijkstra(int t){ priority_queue<Node> que; for(int i=1;i<=n;i++) dis[i]=inf; dis[t]=0; que.push((Node){t,dis[t]}); while(!que.empty()){ Node now=que.top();que.pop(); int x=now.v; if(dis[x]!=now.w)continue; for(int i=Begin[x];~i;i=e[i].next){ int ne=e[i].to; if(dis[ne]>dis[x]+e[i].w){ dis[ne]=dis[x]+e[i].w; que.push((Node){ne,dis[ne]}); } } } } int main(){ while(~scanf("%d%d",&n,&m)&&(n||m)){ INIT(Begin,-1);tot=0; int x,y,w; while(m--){ scanf("%d%d%d",&x,&y,&w); Add(x,y,w); Add(y,x,w); } Dijkstra(1); printf("%d\n",dis[n]); }
return 0; }
|