洛谷 P3183 [HAOI2016] 食物链

这里需要一点点的拓扑知识,然后构建链表。

接着就是一个记忆化搜索。

 

#include <cstdio>
#include <string>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <vector> 
using namespace std;
vector<int>e[100010];
int out[100010],ind[100010],f[100010];
int n,m,a,b,ans;
int dfs(int x)
{
    if (f[x]) return f[x];//////记忆化剪枝 
    int Ans=0;
    if (out[x]==0) return 1;
    for(vector<int>::iterator it=e[x].begin();it!=e[x].end();it++) 
	{
		Ans+=dfs(*it);
	}	
    f[x]=Ans;
    return f[x];
}
main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=m;i++)    
    {
    	scanf("%d%d",&a,&b); 	
		e[a].push_back(b);
		out[a]++,ind[b]++;//入度,出度 
	}
    for (int i=1;i<=n;i++)
        if (ind[i]==0 && out[i]!=0)////注意单独点的情况,单独的一个生物不算食物链 
            ans+=dfs(i);
    printf("%d",ans);
}

 

posted @   浪矢-CL  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
历史上的今天:
2017-07-25 bzoj 1821 部落划分
2017-07-25 图论————最小生成树
2017-07-25 树上最短路
点击右上角即可分享
微信分享提示