【BZOJ4562】【拓扑排序】【DP】[Haoi2016]食物链 题解

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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值