DFS最大食物链计数

洛谷4017最大食物链计数

代码

// https://www.luogu.com.cn/problem/P4017
#include<iostream>
#include<vector>
using namespace std;
vector<int> map[5001];
int dp[5001]={0};
bool is[5001];
int ans  = 0;
int n,m;
const int mod = 80112002;
int dfs(int index){
    if(map[index].size()==0)return dp[index] =1;
    int res = 0;
    for(int i  = 0;i<map[index].size();i++){
        int& ne = map[index][i];//dp永远为1,dp加快速度,dfs遍历index消费者下面的
        res+=dp[ne]?dp[ne]:dfs(ne);
        res%=mod;
    }
    return dp[index] = res;
}
int main(){
    cin>>n>>m;
    int x,y;
    while(m--){
        cin>>x>>y;
        //y吃x
        map[y].push_back(x);//建立二维动态
        is[x] = true;
    }
    for(int i = 1;i<=n;i++){
        if(!is[i]){//如果是消费者
            ans = (ans+dfs(i))%mod;
        }
    }
    cout<<ans;
    return 0;
}

参考

ans

posted @ 2022-11-17 08:36  壹剑霜寒十四州  阅读(11)  评论(0编辑  收藏  举报