Description
如图所示为某生态系统的食物网示意图,据图回答第1小题
现在给你n个物种和m条能量流动关系,求其中的食物链条数。
物种的名称为从1到n编号
M条能量流动关系形如
a1 b1
a2 b2
a3 b3
......
am-1 bm-1
am bm
其中ai bi表示能量从物种ai流向物种bi,注意单独的一种孤立生物不算一条食物链
Input
第一行两个整数n和m,接下来m行每行两个整数ai bi描述m条能量流动关系。
(数据保证输入数据符号生物学特点,且不会有重复的能量流动关系出现)
1<=N<=100000 0<=m<=200000
题目保证答案不会爆 int
Output
一个整数即食物网中的食物链条数
Sample Input
10 16
1 2
1 4
1 10
2 3
2 5
4 3
4 5
4 8
6 5
7 6
7 9
8 5
9 8
10 6
10 7
10 9
Sample Output
91 /**************************************************************
2 Problem: 4562
3 User: Hammer_cwz_77
4 Language: C++
5 Result: Accepted
6 Time:1164 ms
7 Memory:7116 kb
8 ****************************************************************/
9
10 #include<bits/stdc++.h>
11 using namespace std;
12 const int gg=200000+5;
13 struct node{
14 int to;
15 int net;
16 }a[gg];
17 int ans;
18 int head[gg];
19 int n,m;
20 int r[gg],c[gg];
21 int f[gg];
22 int cnt;
23 inline void add(int x,int y)
24 {
25 a[++cnt].to=y;
26 a[cnt].net=head[x];
27 head[x]=cnt;
28 }
29 inline void dfs(int x,int y)
30 {
31 if(f[x])
32 return ;
33 if(!c[x])
34 {
35 f[x]=1;
36 return ;
37 }
38 for(int i=head[x];i;i=a[i].net)
39 {
40 if(a[i].to!=y)
41 {
42 dfs(a[i].to,x);
43 f[x]+=f[a[i].to];
44 }
45 }
46 }
47 int main()
48 {
49 cin>>n>>m;
50 for(int i=1;i<=m;i++)
51 {
52 int a,b;
53 cin>>a>>b;
54 r[b]++;
55 c[a]++;
56 add(a,b);
57 }
58 for(int i=1;i<=n;i++)
59 {
60 if(!r[i]&&c[i])
61 dfs(i,i),
62 ans+=f[i];
63 }
64 cout<<ans<<endl;
65 return 0;
66 }