P3183 [HAOI2016] food chain, p3183haoi2016
Description
For the food network of an ecosystem, according to Figure 1st, I am now giving you a relationship between n species and m energy flows, asking for the number of food chains. The name of the species is from 1 to n, and M pieces of energy flow are like a1 b1a2 b2a3 b3 ...... am-1 bm-1am bm where ai bi indicates that energy flows from species ai to species bi, note that a separate isolated creature is not a food chain
Input/Output Format
Input Format:
The first line has two integers, n and m. The next line has two integers, ai bi, to describe the energy flow relationship of m. (Data ensures the biological characteristics of input data symbols without repeated energy flow relationships) 1 <= N <= 100000 0 <= m <= 200000 questions ensure that the answer will not blow up int
Output Format:
An integer is the number of food chains in the Food Network.
Input and Output sample input sample #1:
10 161 21 41 102 32 54 34 54 86 57 67 98 59 810 610 9
The question tag is written for dynamic planning, but I am yy using A topological sorting + entry/exit statistics method. The first time I handed in ,,
The procedure is simple,
Record two inbound arrays, one for topological sorting, and the other for determining the answer, and then for an outbound degree,
Topological sorting
Finally, just add a sum.
1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<algorithm> 5 #include<queue> 6 using namespace std; 7 const int MAXN=400001; 8 inline void read(int &n) 9 {10 char c=getchar();n=0;bool flag=0;11 while(c<'0'||c>'9') c=='-'?flag=1,c=getchar():c=getchar();12 while(c>='0'&&c<='9') n=n*10+c-48,c=getchar();flag==1?n=-n:n=n;13 }14 struct node15 {16 int u,v,w,nxt;17 }edge[MAXN];18 int head[MAXN];19 int num=1;20 int dp[MAXN];21 int chudu[MAXN];22 int rudu2[MAXN];23 inline void add_edge(int x,int y,int z)24 {25 edge[num].u=x;26 edge[num].v=y;27 edge[num].w=z;28 edge[num].nxt=head[x];29 head[x]=num++;30 }31 int rudu[MAXN];32 int n,m;33 void Topsort()34 {35 queue<int>q;36 int tot=0;37 for(int i=1;i<=n;i++)38 if(!rudu[i]) q.push(i),tot++;39 while(q.size()!=0)40 {41 int p=q.front();42 q.pop();43 for(int i=head[p];i!=-1;i=edge[i].nxt)44 {45 dp[edge[i].v]+=dp[p];46 rudu[edge[i].v]--;47 if(!rudu[edge[i].v] ) q.push(edge[i].v);48 }49 }50 }51 int main()52 {53 memset(head,-1,sizeof(head));54 read(n);read(m);55 for(int i=1;i<=m;i++)56 {57 int a,b;read(a);read(b);58 add_edge(a,b,1);59 rudu[b]++;60 rudu2[b]++;61 chudu[a]++;62 }63 for(int i=1;i<=n;i++)64 if(!rudu[i]) dp[i]=1;65 Topsort();66 int ans=0;67 for(int i=1;i<=n;i++)68 if(chudu[i]==0&&rudu2[i]!=0)69 ans+=dp[i];70 printf("%d",ans);71 return 0;72 }