[洛谷P4017]最大食物链计数

传送门
dp思路非常好想,就是简单的加法原理。但是状态维护的顺序必须按照拓扑序,那么我们就边拓扑排序边更新dp数组就行了。
比如i生物能吃a、b、c三种生物,那么dp[i]=dp[a]+dp[b]+dp[c]
但在此之前我们必须已经求出dp[a,b,c]的值,也就是状态维护应该按照拓扑序。
代码

#include<iostream>
#include<cstdio>
#include<queue>
#define maxn1 500005
#define maxn2 5005
#define modn 80112002
using namespace std;
struct graph{
    int nex, to;
} edge[maxn1];
int head[maxn2], tot;
inline void insert(int from,int to){
    edge[++tot].nex = head[from];
    head[from] = tot;
    edge[tot].to = to;
}
int N, M;
int dp[maxn2],in[maxn2],out[maxn2],ans;
void topo_dp(){
    queue<int> que;
    for (int i = 1; i <= N;i++){
        if(in[i]==0){
            dp[i] = 1;
            que.push(i);
        }
    }
    while(!que.empty()){
        int v = que.front();
        que.pop();
        for (int i = head[v]; i;i=edge[i].nex){
            int to = edge[i].to;
            in[to]--;
            dp[to] += dp[v];
            dp[to] %= modn;
            if(in[to]==0){
                if(out[to]==0){
                    ans += dp[to];
                    ans %= modn;
                }else
                    que.push(to);
            }
        }
    }
}
int main(){
    scanf("%d%d", &N, &M);
    int u, v;
    for (int i = 1; i <= M;i++){
        scanf("%d%d", &u, &v);
        insert(u, v);
        in[v]++;
        out[u]++;
    }
    topo_dp();
    printf("%d", ans);
}
原文地址:https://www.cnblogs.com/sherrlock/p/14244618.html