标签:
.....................用矩阵存.....................
1 int mp[N][N]; 2 bool p[N]; 3 int dist[N]; 4 void dijk(int s , int n) 5 { 6 int i , j , k ; 7 for( i = 1 ; i <= n ;i++) 8 { 9 p[i] = false; 10 dist[i] = mp[s][i]; 11 } 12 p[s] = true; 13 dist[s] = 0; 14 for(i = 1 ; i < n ; i++) 15 { 16 int Min = INF; 17 int k = 0 ; 18 for( j = 1 ; j <= n ;j++) 19 { 20 if(!p[j]&&dist[j]<Min) 21 { 22 Min = dist[j]; 23 k = j; 24 } 25 } 26 if(Min==INF) return ; 27 p[k] = true; 28 for(j = 1 ; j <= n ;j++) 29 { 30 if(!p[j]&&mp[k][j]!=INF&&dist[j]>dist[k]+mp[k][j]) 31 dist[j] = dist[k]+mp[k][j]; 32 } 33 } 34 }
..............用链表存.................
1 struct Edge{ 2 int to; 3 int v ; 4 int next; 5 }edge[M]; 6 int Enct; 7 int head[N]; 8 void add(int from ,int to , int v ) 9 { 10 edge[Enct].to = to ; 11 edge[Enct].v = v ; 12 edge[Enct].next = head[from]; 13 head[from] = Enct++; 14 15 edge[Enct].to = from ; 16 edge[Enct].v = v ; 17 edge[Enct].next = head[to]; 18 head[to] = Enct++; 19 } 20 void init () 21 { 22 Enct = 0; 23 memset(head,-1, sizeof(head)); 24 } 25 int dist[N]; 26 bool p[N]; 27 void dijk(int s, int n) 28 { 29 int i , j , k ; 30 for( i = 1 ; i <= n ; i++ ) 31 { 32 p[i] = false; 33 dist[i]= INF; 34 } 35 p[s] = true; 36 dist[s] = 0; 37 for( i = head[s] ; i != -1 ; i = edge[i].next) 38 { 39 Edge e = edge[i]; 40 if(e.v<dist[e.to])//考虑重边 41 dist[e.to] = e.v; 42 } 43 for( i = 1 ;i < n ;i++) 44 { 45 int Min = INF; 46 int k = 0 ; 47 for( j = 1 ; j <= n ; j++) 48 { 49 if(!p[j]&&dist[j]<Min) 50 { 51 Min = dist[j]; 52 k = j; 53 } 54 } 55 p[k] = true; 56 if(Min == INF) return ; 57 for( j = head[k] ;j!=-1 ;j=edge[j].next) 58 { 59 Edge e = edge[j]; 60 if(!p[e.to]&&dist[e.to]>dist[k]+e.v) 61 { 62 dist[e.to] = dist[k]+e.v; 63 } 64 } 65 } 66 }
标签:
原文地址:http://www.cnblogs.com/shanyr/p/4671754.html