A Walk Through the Forest dijkstra(邻接矩阵)
http://acm.hdu.edu.cn/showproblem.php?pid=1142
dijkstra(邻接矩阵)
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 using namespace std; 5 const int INF=1<<29; 6 const int MAXN=1000+5; 7 int v[MAXN],d[MAXN]; 8 int w[MAXN][MAXN]; 9 int n,m; 10 void dijkstra() 11 { 12 memset(v,0,sizeof(v)); 13 for(int i=1;i<=n;i++) d[i]=INF; 14 d[2]=0; 15 for(int i=1;i<=n;i++) 16 { 17 int x,m=INF; 18 for(int y=1;y<=n;y++) if(!v[y]&&d[y]<=m) m=d[x=y]; 19 v[x]=1; 20 for(int y=1;y<=n;y++) if(d[y]>d[x]+w[x][y]) d[y]=d[x]+w[x][y]; 21 } 22 } 23 int roat[MAXN]; 24 int dfs(int i) 25 { 26 int j,ans=0; 27 if(roat[i]!=0) return roat[i]; 28 if(i==2) return 1; 29 for(j=1;j<=n;j++) if(w[i][j]!=INF&&d[i]>d[j]) 30 { 31 roat[j]=dfs(j); 32 ans+=dfs(j); 33 } 34 return roat[i]=ans; 35 } 36 int main() 37 { 38 int i,j,a,b,wl; 39 while(cin>>n&&n) 40 { 41 cin>>m; 42 for(i=1;i<=n;i++) 43 for(j=1;j<=n;j++) 44 w[i][j]=INF; 45 for(i=0;i<m;i++) {scanf("%d%d%d",&a,&b,&wl);w[a][b]=wl;w[b][a]=wl;} 46 dijkstra(); 47 memset(roat,0,sizeof(roat)); 48 dfs(1); 49 cout<<roat[1]<<endl; 50 } 51 return 0; 52 }