20c Dijkstra?
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 无向 最短路 3 spfa 4 */ 5 #include<stdio.h> 6 #include<string.h> 7 #include<iostream> 8 #include<algorithm> 9 #include<queue> 10 #include<stack> 11 #define maxn 100005 12 const long long inf = 12345678987654321LL; 13 typedef long long ll; 14 using namespace std; 15 int head[ maxn*2 ],vis[ maxn*2 ],path[ maxn*2 ]; 16 ll dis[ maxn*2 ]; 17 struct node{ 18 int v,next; 19 ll val; 20 }edge[ maxn*2 ]; 21 int pindex; 22 void init(){ 23 pindex=0; 24 memset(head,-1,sizeof(head)); 25 memset(path,-1,sizeof(path)); 26 } 27 void addedge(int u,int v,ll val){ 28 edge[pindex].v=v; 29 edge[pindex].val=val; 30 edge[pindex].next=head[u]; 31 head[u]=pindex++; 32 33 edge[pindex].v=u; 34 edge[pindex].val=val; 35 edge[pindex].next=head[v]; 36 head[v]=pindex++; 37 } 38 void output(int n){ 39 int id=n; 40 stack<int>s; 41 s.push(n); 42 //for(int i=0;i<n*n*n;i++)cout<<path[i]<<endl; 43 while(path[id]!=-1){ 44 s.push(path[id]);//printf("%d ",path[id]); 45 id=path[id]; 46 } 47 printf("%d",s.top());s.pop(); 48 while(!s.empty()){ 49 printf(" %d",s.top()); 50 s.pop(); 51 } 52 printf("\n"); 53 } 54 55 void spfa( int n ){ 56 for( int i=1;i<=n;i++ ) dis[ i ]=inf; 57 dis[1]=0; 58 memset( vis,0,sizeof(vis) ); 59 vis[1]=1; 60 queue<int>q; 61 q.push(1); 62 while(!q.empty()){ 63 int id; 64 id = q.front(); 65 q.pop(); 66 vis[ id ]=0; 67 for(int i=head[ id ];i!=-1;i=edge[i].next ){ 68 int v; 69 v=edge[i].v; 70 if(dis[v]>dis[id]+edge[i].val){ 71 dis[v]=dis[id]+edge[i].val; 72 path[v]=id; 73 if(vis[v]==0){ 74 vis[v]=1; 75 q.push(v); 76 //path[v]=i; 77 } 78 } 79 } 80 } 81 if(dis[n]>=inf) 82 printf("-1\n"); 83 else{ 84 output(n); 85 } 86 return ; 87 } 88 89 int main(){ 90 int n,m; 91 cin>>n>>m; 92 init(); 93 while( m-- ){ 94 int a,b; 95 ll c; 96 cin>>a>>b>>c; 97 addedge(a,b,c); 98 } 99 spfa( n ); 100 return 0; 101 }
keep moving...