zoukankan      html  css  js  c++  java
  • 【luogu P4017 最大食物链计数】 题解

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

    DAG + DP

    #include <queue>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    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;
    }
    
  • 相关阅读:
    LintCode "Maximum Gap"
    LintCode "Wood Cut"
    LintCode "Expression Evaluation"
    LintCode "Find Peak Element II"
    LintCode "Remove Node in Binary Search Tree"
    LintCode "Delete Digits"
    LintCode "Binary Representation"
    LeetCode "Game of Life"
    LintCode "Coins in a Line"
    LintCode "Word Break"
  • 原文地址:https://www.cnblogs.com/MisakaAzusa/p/9648933.html
Copyright © 2011-2022 走看看