标签:
dijkstra(迪杰斯特拉)最短路算法是一种时间复杂度经过严格证明的最短路算法。
优化在于每次取最小值的时候采用堆优化,但是在最短路松弛过程中,dist是不断修改的,所以,为了能使复杂度降到O(nlogn),dist修改的同时,在堆中也要修改。
注意dijkstra(迪杰斯特拉)最短路算法只能用于正权边。
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 using namespace std; 6 7 const int maxn=10001; 8 const int maxm=400002; 9 int n,m; 10 int dist[maxn]; 11 12 int len; 13 int Head[maxn],Next[maxm],Adj[maxm],Weight[maxm]; 14 int c; 15 16 int pos[maxn]; 17 18 struct node 19 { 20 int dist,id; 21 }heap[maxn]; 22 23 void pushdown(int x) 24 { 25 int i; 26 while((i=x<<1)<=len)//len 27 { 28 if(i<len&&heap[i].dist>heap[i+1].dist)i++;//i<len 29 if(heap[i].dist<heap[x].dist) 30 { 31 swap(heap[i],heap[x]); 32 pos[heap[i].id]=i; 33 pos[heap[x].id]=x; 34 x=i; 35 } 36 else break; 37 } 38 } 39 40 void build() 41 { 42 for(int i=1;i<=n;i++) 43 { 44 heap[i].dist=dist[i]; 45 heap[i].id=i; 46 pos[i]=i; 47 } 48 for(int i=n/2;i>=1;i--) 49 pushdown(i); 50 } 51 52 void adjust(int id) 53 { 54 int i=pos[id]; 55 heap[i].dist=dist[id]; 56 while(i>1&&heap[i].dist<heap[i/2].dist) 57 { 58 swap(heap[i],heap[i/2]); 59 i/=2; 60 pos[heap[i*2].id]=i*2; 61 } 62 pos[id]=i; 63 } 64 65 int taketop() 66 { 67 int top=heap[1].id; 68 heap[1]=heap[len--]; 69 pushdown(1); 70 return top; 71 } 72 73 void AddEdge(int u,int v,int w) 74 { 75 c++; 76 Adj[c]=v; 77 Next[c]=Head[u]; 78 Weight[c]=w;// 79 Head[u]=c; 80 } 81 82 void dijkstra(int s) 83 { 84 memset(dist,0x7f7f7f7f,sizeof(dist)); 85 dist[s]=0; 86 build();// 87 for(int a=1;a<=n;a++) 88 { 89 int p=taketop(); 90 for(int i=Head[p];i;i=Next[i]) 91 { 92 int v=Adj[i]; 93 if(dist[v]>dist[p]+Weight[i]) 94 { 95 dist[v]=dist[p]+Weight[i]; 96 adjust(v); 97 } 98 } 99 } 100 101 } 102 103 int main() 104 { 105 freopen("dijkstra.in","r",stdin); 106 freopen("dijkstra.out","w",stdout); 107 scanf("%d %d",&n,&m); 108 int s,e; 109 scanf("%d %d",&s,&e); 110 len=n; 111 for(int i=1;i<=m;i++) 112 { 113 int a,b,w; 114 scanf("%d %d %d",&a,&b,&w); 115 AddEdge(a,b,w); 116 AddEdge(b,a,w); 117 } 118 dijkstra(s); 119 // for(int i=1;i<=n;i++) 120 // printf("%d: %d\n",i,dist[i]); 121 printf("%d",dist[e]); 122 return 0; 123 }
标签:
原文地址:http://www.cnblogs.com/cnblogsLSY/p/5778694.html