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
9
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <stack>
#define INF 2147483647
#define LL long long
#define clr(x) memset(x, 0, sizeof x)
#define ms(a, x) memset(x, a, sizeof x)
#define digit (ch < '0' || ch > '9')
using namespace std;
template <class T> inline void read(T &x) {
int flag = 1; x = 0;
register char ch = getchar();
while( digit) { if(ch == '-') flag = -1; ch = getchar(); }
while(!digit) { x = (x<<1)+(x<<3)+ch-'0'; ch = getchar(); }
x *= flag;
}
const int maxn = 100010;
queue<int> q;
int n,m,x,y,ans,tot;
int head[maxn],ind[maxn],oud[maxn],f[maxn],to[maxn<<1],nxt[maxn<<1];
inline void add(int x, int y) { to[++tot] = y , nxt[tot] = head[x] , head[x] = tot; }
int main() {
read(n); read(m);
for(int i = 1; i <= m; i++) read(x), read(y), add(x, y), ind[x]++, oud[y]++;
for(int i = 1; i <= n; i++) if(!oud[i]) f[i] = ind[i] ? 1 : 0, q.push(i);
while(!q.empty()) {
x = q.front(), q.pop();
for(int i = head[x]; i; i = nxt[i]) {
f[to[i]] += f[x], oud[to[i]]--;
if(!oud[to[i]]) q.push(to[i]);
}
}
for(int i = 1; i <= n; i++) if(!ind[i]) ans += f[i];
printf("%d\n",ans);
return 0;
}