P4017 最大食物链计数(拓扑排序)

测试链接:https://www.luogu.com.cn/record/224653356

思路

利用出度是否为0,判断是否是食物链顶端,利用dp的思想,累加前面的路径

题解

拓扑排序 +stl队列

#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
const int mod = 80112002;
typedef long long ll;
int t,n,m;
int dp[N];
int indg[N];
queue<int>que;
ll ans=0;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    vector<vector<int>>edges(n+10);
    for(int i=0;i<m;i++)
    {
        int f,t;
        cin>>t>>f;
        edges[f].push_back(t);
        indg[t]++;
    }

    for(int i=1;i<=n;i++)
    {
        if(indg[i]==0)
        {
            dp[i]++;
            que.push(i);
        }
    }

    // for(int i=1;i<=n;i++)
    // {
    //     for(auto it:edges[i])cout<<it<<' ';
    // }

    
    while(!que.empty())
    {
        int cur = que.front();
        que.pop();
        if(edges[cur].size()==0)ans=(ans+dp[cur])%mod;
        else 
        {
            for(auto id:edges[cur])
            {
                dp[id]=(dp[id]+dp[cur])%mod;
                if(--indg[id]==0)que.push(id);
            }
        }

    }
    cout<<ans<<endl;
    return 0;
}

拓扑排序+链式前向星+stl队列

#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
const int M=5e5+10;
const int mod = 80112002;
typedef long long ll;
int t,n,m;
int dp[N];
int indg[N];
queue<int>que;
int head[N];
int to[M];
int nt[M];

ll ans=0;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int f,t;
        cin>>t>>f;
        nt[i]=head[f];
        to[i]=t;
        head[f]=i;
        indg[t]++;
    }

    for(int i=1;i<=n;i++)
    {
        if(indg[i]==0)
        {
            dp[i]++;
            que.push(i);
        }
    }

    // for(int i=1;i<=n;i++)
    // {
    //     for(auto it:edges[i])cout<<it<<' ';
    // }

    
    while(!que.empty())
    {
        int cur = que.front();
        que.pop();
        if(head[cur]==0)ans=(ans+dp[cur])%mod;
        else 
        {
            for(int i=head[cur];i!=0;i=nt[i])
            {
                dp[to[i]]=(dp[to[i]]+dp[cur])%mod;
                if(--indg[to[i]]==0)que.push(to[i]);
            }
        }

    }
    cout<<ans<<endl;
    return 0;
}
posted @ 2025-07-16 10:43  屈臣  阅读(14)  评论(0)    收藏  举报