【bzoj4562】[Haoi2016]食物链 记忆化搜索

来源:互联网 发布:互补滤波算法详解 编辑:程序博客网 时间:2024/05/22 13:34

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 161 21 41 102 32 54 34 54 86 57 67 98 59 810 610 710 9

Sample Output

9

HINT

Source


更点水题除除草

身为一个SB,表示这种题竟然没一眼秒……

记忆化搜索SB题啊…

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef long long LL;const int SZ = 400010;const int INF = 1000000010;int in[SZ],out[SZ];LL dp[SZ];int head[SZ],nxt[SZ],to[SZ];void build(int f,int t){    static int tot = 1;    to[++ tot] = t;    nxt[tot] = head[f];    head[f] = tot;}LL dfs(int u){    if(dp[u]) return dp[u];    LL ans = 0;    if(out[u] == 0 && in[u]) ans ++;    for(int i = head[u];i;i = nxt[i])        ans += dfs(to[i]);    return dp[u] = ans;}int main(){    int n,m;    scanf("%d%d",&n,&m);    for(int i = 1;i <= m;i ++)    {        int a,b;        scanf("%d%d",&a,&b);        build(a,b);        in[b] ++; out[a] ++;    }    LL ans = 0;    for(int i = 1;i <= n;i ++)        if(!in[i])            ans += dfs(i);    printf("%lld\n",ans);    return 0;}
0 0