[Luogu] P4017 Maximum Food Chain Count (Topological Sort)

[Luogu] P4017 Maximum Food Chain Count

Topic background

Do you know the food chain? In Delia's biology exam, all the questions about counting food chains were wrong because she always counted or missed a few. So she came to ask you for help, but you won't! Write a program to help her.

Title description

Given you a food web, you ask for the number of the largest food chain in this food web.

(The "largest food chain" here refers to the food chain in the biological sense, that is, the far left is the producer who will not prey on other organisms, and the far right is the consumer who will not be preyed by other organisms.)

Delia is very anxious, so you only have 1 second.

Since this result may be too large, you only need to output the result of the total modulo 80112002.

Input format

The first line, two positive integers n and m, represent the biological species n and the relationship between eating and being eaten m.

In the next m lines, each line has two positive integers, indicating the creature A that was eaten and the creature B that ate A.

Output format

An integer per line is the result of the maximum number of food chains modulo 80112002.

Sample input and output

enter
5 7
1 2
1 3
2 3
3 5
2 5
4 5
3 4
Output
5

Instructions/tips

Insert picture description here

Ideas

Topological sorting uses an array to store the number of food chains at each point.
Find the sum of the number of food chains at the point with degree 0.

Code

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
long long ans[5010],sum=0,tot=0,n,m,head[5010],ins[5010];
bool outs[5010];
queue<long long> q;
struct jgt
{
    
    
	long long x,y,nxt;
}f[500010];
void input()
{
    
    
	long long i,j,t;
	memset(ins,0,sizeof(ins));
	memset(outs,true,sizeof(outs));
	memset(ans,0,sizeof(ans));
	scanf("%lld%lld",&n,&m);
	for(i=1;i<=m;i++)
	{
    
    
		tot++;
		scanf("%lld%lld",&f[tot].x,&f[tot].y);
		f[tot].nxt=head[f[tot].x];
		head[f[tot].x]=tot;
		ins[f[tot].y]++;
		outs[f[tot].x]=0;
	}
	return;
}
void topsort()
{
    
    
	long long i;
	for(i=1;i<=n;i++)
		if(!ins[i])
		{
    
    
			q.push(i);
			ans[i]=1;
		}
	for(;!q.empty();q.pop(),sum++)
	{
    
    
		for(i=head[q.front()];i;i=f[i].nxt)//更新入度 
		{
    
    
			ins[f[i].y]--;
			ans[f[i].y]=(ans[f[i].y]+ans[q.front()])%80112002;//统计食物链条数 
			if(!ins[f[i].y])//当能够到达这个点的所有点都遍历过后将这个点加入队列
				q.push(f[i].y);
		}
	}
	return;
}
void output()
{
    
    
	long long i,answer=0;
	for(i=1;i<=n;i++)//统计食物链条数
		if(outs[i])//出度为0 
			answer=(answer+ans[i])%80112002;
	printf("%lld",answer);
	return;
}
int main()
{
    
    
	input();
	topsort();
	output();
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46975572/article/details/112887433