大白书P330
#include <iostream> #include <cstdio> #include <algorithm> #include <string.h> #include <vector> #include <queue> using namespace std; const int maxn = 1000+10; const int INF = 1000000000; struct Edge{ int from,to,dist; }; struct HeapNode{ int d,u; bool operator <(const HeapNode &rhs)const { return d>rhs.d; } }; struct Dijkstra{ int n,m; vector<Edge> edges; vector<int>G[maxn]; bool done[maxn]; int d[maxn]; int p[maxn]; void inti(int n){ this->n=n; for(int i=0; i < n; ++i) G[i].clear(); edges.clear(); } void AddEdge(int from, int to, int dist){ edges.push_back((Edge){from,to,dist}); int m =edges.size(); G[from].push_back(m-1); } void dijkstra(int s){ priority_queue<HeapNode> Q; for(int i=0; i<n; i++) d[i]=INF; d[s] = 0; memset(done, false,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}); } } } } }solve1; vector<int> R[maxn]; int dp[maxn]; int dfs(int u){ if(dp[u]!=-1) return dp[u]; if(u==1) return 1; dp[u]=0; for(int i =0 ; i<R[u].size(); i++){ int v = R[u][i]; dp[u]+=dfs(v); } return dp[u]; } int main() { int n,m; while(scanf("%d",&n)==1&&n){ scanf("%d",&m); solve1.inti(n); for(int i = 0; i<m; ++i){ int u,v,d; scanf("%d%d%d",&u,&v,&d); u--,v--; solve1.AddEdge(u,v,d); solve1.AddEdge(v,u,d); } solve1.dijkstra(1); for(int i = 0; i<n; i++) R[i].clear(); for(int i = 0; i < solve1.edges.size(); ++i){ int u=solve1.edges[i].from, v=solve1.edges[i].to; if(solve1.d[u]>solve1.d[v]) R[u].push_back(v); } memset(dp,-1,sizeof(dp)); printf("%d\n",dfs(0)); } return 0; }
时间: 2024-10-31 12:09:17