Los examples Valley P4017 : HTTPS: //www.luogu.com.cn/problem/P4017
Seeking the maximum number of the food chain, the biggest problem has been given in the definition of the food chain, the chain can be converted to a defined starting point is the point of 0 degree, a 0 degree point as the end point. Note the food web abstract of a directed graph may have more.
Idea: Just once topological sorting, dynamic cumulative record your answers to the final output to the maximum cumulative number to the end of the food chain.
template:
1 bool toposort() { 2 q = new queue(); 3 for (i = 0; i < n; i++) 4 if (in_deg[i] == 0) q.push(i); 5 ans = new vector(); 6 while (!q.empty()) { 7 u = q.pop(); 8 ans.push_back(u); 9 for each edge(u, v) { 10 if (--in_deg[v] == 0) q.push(v); 11 } 12 } 13 if (ans.size() == n) { 14 for (i = 0; i < n; i++) 15 std::cout << ans[i] << std::endl; 16 return true; 17 } else { 18 return false; 19 } 20 }
AC Code:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int maxn = 5e3+5; 5 const ll mod = 80112002; 6 struct node{ 7 vector<int> v; 8 int in,out; 9 }g[maxn]; 10 int n,m; 11 ll ans[maxn]; 12 void add(int u,int v){ 13 g[v].v.push_back(u); 14 g[v].out++,g[u].in++; 15 } 16 void toposort(){ 17 queue<int> q; 18 for(int i = 1;i<=n;i++) if(!g[i].in ) q.push(i),ans[i] = 1; 19 while(!q.empty()){ 20 int cur = q.front(); 21 q.pop(); 22 for(int i = 0;i<g[cur].v.size();i++){ 23 int u = g[cur].v[i]; 24 ans[u] = (ans[u] + ans[cur])%mod; 25 if(--g[u].in == 0) q.push(u); 26 } 27 } 28 } 29 int main(){ 30 scanf("%d%d",&n,&m); 31 for(int i = 1;i<=m;i++){ 32 int u,v; 33 scanf("%d%d",&u,&v); 34 add(u,v); 35 } 36 toposort(); 37 ll res = 0; 38 for(int i = 1;i<=n;i++){ 39 if(!g[i].out ) res = (res+ans[i])%mod; 40 } 41 cout<<res; 42 return 0; 43 }