【luogu P4017 最大食物链计数】 题解

题目链接:https://www.luogu.org/problemnew/show/P4017

DAG + DP

#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 500010;
const int mod = 80112002;
struct edge{
    long long from, to, next;
}e[maxn<<2];
long long head[maxn], cnt;
long long n, m, indrg[maxn], outdrg[maxn], f[maxn], str[maxn], strnum, end[maxn], endnum, ans;
long long H, T, Q[maxn];
void add(long long u, long long v)
{
    e[++cnt].from = u;
    e[cnt].next = head[u];
    e[cnt].to = v;
    head[u] = cnt;
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%lld%lld",&n,&m);
    for(long long i = 1; i <= m; i++)
    {
        long long u, v;
        scanf("%lld%lld",&u,&v);
        add(u, v);
        indrg[v]++; outdrg[u]++;
    }
    T = 0, H = 1;
    for(long long i = 1; i <= n; i++)
    {
        if(indrg[i] == 0)
        Q[++T] = i, str[++strnum] = i;
        if(outdrg[i] == 0)
        end[++endnum] = i;
    }
        
    while(H <= T)
    {
        long long u = Q[H++];
        for(long long i = head[u]; i != -1; i = e[i].next)
        {
            long long v = e[i].to;
            indrg[v]--;
            if(indrg[v] == 0)
            Q[++T] = v;
        }
    }
    
    for(int i = 1; i <= strnum; i++)
    f[str[i]] = 1;
    
    for(long long i = 1; i <= n; i++)
    {
        long long u = Q[i];
        for(long long j = head[u]; j != -1; j = e[j].next)
        {
            long long v = e[j].to;
            f[v] += f[u] % mod;
        }
    }
    
    for(int i = 1; i <= endnum; i++)
    ans += f[end[i]] % mod;
    
    printf("%lld",ans % mod);
    return 0;
}

转载于:https://www.cnblogs.com/MisakaAzusa/p/9648933.html

你可能感兴趣的:(【luogu P4017 最大食物链计数】 题解)