Luogu P4017 最大食物链计数【拓扑排序】

在这里插入图片描述

思路

我们要设两个数组分别记录它的入度和出度,
在拓扑排序时判断它是否是最高级消费者(入度出度都为0),
就把它的总链数加起来。

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;

int rd[1000010],cd[1000010],ls[1000010],dl[1000010],v[1000010],js[1000010];
int n,m,x,y,tot,ans;

struct node
{
    
    
	int y,next;
}a[1000010];
void ljb(int x,int y)
{
    
    
	a[++tot]=(node){
    
    y,ls[x]};
	ls[x]=tot;
}
void tp()
{
    
    
	int hd=0,tl=0;
	for(int i=1; i<=n; i++)
	 if(rd[i]==0)
	   dl[++tl]=i,v[i]=1,js[i]=1;
	while(hd<tl)
	 {
    
    
	 	hd++;
	 	int y=dl[hd];
	 	for(int i=ls[y]; i; i=a[i].next)
	 	 {
    
    
	 	 	int yy=a[i].y;
	 	 	if(v[yy]==1)
	 	 	  continue;
	 	 	rd[yy]--;
	 	 	js[yy]+=js[y];
	 	 	js[yy]%=80112002;
	 	 	if(rd[yy]==0)
	 	 	 {
    
    
	 	 	   if(cd[yy]==0)
	 	 	    {
    
    
	 	 	      ans+=js[yy];
	 	 	      ans%=80112002;
	 	 	    }
	 	 	   dl[++tl]=yy,v[yy]=1;
	 	 	 }
	 	 }
	 }
}
int main()
{
    
    
    cin>>n>>m;
    for(int i=1; i<=m; i++)
     {
    
    
     	scanf("%d%d",&x,&y);
     	ljb(x,y);
     	rd[y]++;
     	cd[x]++;
     }
    tp();
    cout<<ans;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Jackma_mayichao/article/details/108052684