标签:
A Walk Through the ForestUniversity of Waterloo Local Contest 2005.09.24
Dijkstra
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<vector> #include<queue> using namespace std; int n,m; const int maxn=2010; const int inf=0x3ffffff; int cost[maxn][maxn]; int num[maxn]; bool uesd[maxn]; int d[maxn]; void dijkstra(int s) { for(int i=0;i<=n;i++) { d[i]=inf; uesd[i]=0; } d[s]=0; while(1){ int v=-1; for(int i=1;i<=n;i++) { if(!uesd[i]&&(v==-1||d[i]<d[v])) {v=i;} } uesd[v]=1; if(v==-1) break; for(int i=1;i<=n;i++) { if(d[i]>d[v]+cost[i][v]) {d[i]=d[v]+cost[i][v];} } } } int bfs(int s) { if(num[s]) return num[s]; if(s==2) return 1; int sum=0; for(int i=1;i<=n;i++) { if(cost[s][i]<inf&&d[s]>d[i]){ if(num[i]) sum=sum+num[i]; else sum=sum+bfs(i); } } sum=sum+num[s]; num[s]=sum; return num[s]; } int main() { int a,b,c; while(1){ scanf("%d",&n); if(!n) break; for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) cost[i][j]=inf; for(int i=0;i<=n;i++) cost[i][i]=0; scanf("%d",&m); for(int i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); cost[a][b]=cost[b][a]=c; } dijkstra(2); memset(num,0,sizeof(num)); printf("%d\n",bfs(1)); }
Heap+Dijkstra
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<vector> #include<queue> using namespace std; int n,m; const int maxn=2007; const int inf=0x3fffffff; bool flag[maxn][maxn]; int num[maxn]; struct HeapNode { int d,u; HeapNode(int dd,int uu):d(dd),u(uu){} bool operator < (const HeapNode& rhs) const{ return d>rhs.d; } }; struct Edge { int from,to,dist; Edge(int u,int v,int d):from(u),to(v),dist(d){} }; vector<Edge> edges; vector<int> G[maxn]; bool done[maxn]; int d[maxn],p[maxn]; void init(){ for(int i=0;i<=n;i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int to,int dist) { int mm; edges.push_back(Edge(from,to,dist)); mm=edges.size(); G[from].push_back(mm-1); } void dijkstra(int s) { priority_queue<HeapNode> Q; for(int i=0;i<=n;i++) d[i]=inf; d[s]=0; memset(done,0,sizeof(done)); Q.push(HeapNode(0,s)); while(!Q.empty()){ HeapNode x=Q.top();Q.pop(); int u=x.u; if(done[u]) continue; done[u]=true; for(int i=0;i<G[u].size();i++){ Edge& e=edges[G[u][i]]; if(d[e.to]>d[u]+e.dist){ d[e.to]=d[u]+e.dist; p[e.to]=G[u][i]; Q.push(HeapNode(d[e.to],e.to)); } } } } int bfs(int s) { if(num[s]) return num[s]; if(s==2) return 1; int sum=0; for(int i=1;i<=n;i++) { if(flag[s][i]&&d[s]>d[i]){ if(num[i]) sum=sum+num[i]; else sum=sum+bfs(i); } } sum=sum+num[s]; num[s]=sum; return num[s]; } int main() { int a,b,c; while(1){ memset(flag,0,sizeof(flag)); scanf("%d",&n); init(); if(!n) break; scanf("%d",&m); for(int i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); AddEdge(a,b,c); AddEdge(b,a,c); flag[a][b]=flag[b][a]=1; } dijkstra(2); memset(num,0,sizeof(num)); int ans=0; int sum=d[1]; for(int i=3;i<=n;i++) { if(d[i]<sum) ans++; } printf("%d\n",bfs(1)); } }
标签:
原文地址:http://blog.csdn.net/yuanchang_best/article/details/43156625