P4017 最大食物链计数

原题链接

题解

首先这题是一个有向无环图,如图,每个结点上方显示的是到达该节点的路径数,我们不难发现每个结点的路径数都由其入度结点的路径数之和,最终得出5结点的路径数。那么由此我们只需要求出每个无出度结点的路径数再相加即可。

 code

 

#include<bits/stdc++.h>
using namespace std;
const int N=5e5+5;
const int M=80112002;
int cnt=0;
int head[5005],Next[N],to[N],sum[5005],pre_sum[5005],que[5005];
void build(int x,int y){
    Next[++cnt]=head[x];
    head[x]=cnt;
    to[cnt]=y;
    sum[y]++;
}
int main(){
    int n,m,l=0,r=0;
    cin>>n>>m;
    for (int i=1;i<=m;i++){
        int x,y;
        cin>>x>>y;
        build(x,y);
    }
    for (int i=1;i<=n;i++){
        if (sum[i]==0){
            que[r++]=i;
            pre_sum[i]=1;
        }
    }
    int ans=0;
    while (l<r){
        int from=que[l++];
        if (head[from]==0) ans=(ans+pre_sum[from])%M;  //出度为零,说明要进行累加了
        for (int i=head[from];i>0;i=Next[i]){
            if (--sum[to[i]]==0) que[r++]=to[i];
            pre_sum[to[i]]=(pre_sum[to[i]]+pre_sum[from])%M;  //同余原理
        }
    }
    cout<<ans<<endl;
    return 0;
} 

 

posted @ 2024-02-27 19:16  黑屿白  阅读(21)  评论(0)    收藏  举报