码迷,mamicode.com
首页 > 其他好文 > 详细

bzoj4562 [Haoi2016]食物链

时间:2017-09-22 16:34:22      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:关系   names   scanf   memory   记忆化   描述   string   编号   scan   

4562: [Haoi2016]食物链

Time Limit: 10 Sec  Memory Limit: 128 MB

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

HINT

 

Source

 

Tip:

  比较简单的一道题;

  只要找到每条食物链的顶端;

  做记忆化搜索就行了;

 

Code:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define MAXN 200008
using namespace std;

int n,m,tot,in[MAXN],out[MAXN],head[MAXN],next[MAXN],vet[MAXN];
long long dp[MAXN],res;

void add(int x,int y){
    tot++;
    next[tot]=head[x];
    head[x]=tot;
    vet[tot]=y;
}

long long dfs(int u){
    if(dp[u]!=0) return dp[u];
    long long ans=0;
    if(out[u]==0&&in[u]) ans++;
    for(int i=head[u];i;i=next[i])
        ans+=dfs(vet[i]);
    dp[u]=ans;
    return ans;
}

int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        add(x,y);
        out[x]++; in[y]++;
    }
    
    for(int i=1;i<=n;i++)
        if(!in[i]){
            res+=dfs(i);
        }
    printf("%lld",res);
}

 

bzoj4562 [Haoi2016]食物链

标签:关系   names   scanf   memory   记忆化   描述   string   编号   scan   

原文地址:http://www.cnblogs.com/WQHui/p/7575532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!