poj 2378 (dijkstra)
http://poj.org/problem?id=2387
一个dijkstra的模板题
#include <stdio.h> #include <string.h> #define inf 999999; int graph[ 1005 ][ 1005 ]; bool mark[ 1005 ]; int m,n; void dijkstra() { int d[ 1005 ],k,Min; bool mark[ 1005 ]; for(int i = 1 ; i <= n ; i++) //对d[i]进行初始化 { mark[ i ] = false; d[ i ] = graph[ 1 ][ i ]; } for(int i = 1 ; i <= n ; i++)
{ Min=inf; for(int j = 1 ; j <= n ; j++) { if(!mark[ j ] && d[ j ] < Min) { k = j; Min = d[ j ]; } } mark[ k ] = true; for(int j = 1 ; j <= n ; j++) { if(!mark[ j ] && d[ j ] > graph[ k ][ j ] + d[ k ]) d[ j ] = graph[ k ] [ j ] + d[ k ]; } } printf("%d\n",d[n]); } int main() { int a,b,c; while(~scanf("%d%d",&m,&n)){ for(int i = 0 ; i <= n ; i++) for(int j = 0 ; j <= n ; j++) if(i == j) graph[ i ][ j ] = 0; else { graph[ i ][ j ] = inf; graph[ j ][ i ] = inf; } for(int i = 1 ; i <= m ;i++) { scanf("%d%d%d",&a,&b,&c); if(graph[ a ][ b ] > c) { graph[ a ][ b ] = c; graph[ b ][ a ] = c; } } dijkstra(); } return 0; }
dijkstra +head
1 const int N=405; 2 struct rec 3 { 4 int v,w;//v代表所连的值,W代表权值 5 }; 6 7 8 vector<rec> edge[N*N]; 9 int n,st,ed; 10 long long dis[N*N]; 11 bool vis[N*N]; 12 13 struct cmp 14 { 15 bool operator()(int a,int b) 16 { 17 return dis[a]>dis[b]; 18 } 19 }; 20 21 void Dijkstra() 22 { 23 priority_queue<int,vector<int>,cmp> Q; 24 memset(dis,-1,sizeof(dis)); 25 memset(vis,0,sizeof(vis)); 26 int i,u,v; 27 Q.push(st); 28 dis[st]=1; 29 while(!Q.empty()) 30 { 31 u=Q.top(); 32 Q.pop(); 33 vis[u]=0; 34 if(u==st) 35 break; 36 if(dis[v]==-1 || dis[v]<dis[u]*edge[u][i].w) 37 { 38 dis[v]=dis[u]*edge[u][i].w; 39 if(!vis[v]) 40 { 41 vis[v]=1; 42 Q.push(v); 43 } 44 } 45 } 46 } 47 } 48 for(i=0; i<edge[u].size(); i++) 49 { 50 v=edge[u][i].v; 51 if(dis[v]==-1 || dis[v]<dis[u]*edge[u][i].w) 52 { 53 dis[v]=dis[u]*edge[u][i].w; 54 if(!vis[v]) 55 { 56 vis[v]=1; 57 Q.push(v); 58 } 59 } 60 } 61 } 62 }