P4017 最大食物鏈計數(拓撲排序)

P4017 最大食物鏈計數
題目背景
你知道食物鏈嗎?Delia 生物考試的時候,數食物鏈條數的題目全都錯了,因爲她總是重複數了幾條或漏掉了幾條。於是她來就來求助你,然而你也不會啊!寫一個程序來幫幫她吧。

題目描述
給你一個食物網,你要求出這個食物網中最大食物鏈的數量。

(這裏的“最大食物鏈”,指的是生物學意義上的食物鏈,即最左端是不會捕食其他生物的生產者,最右端是不會被其他生物捕食的消費者。)

Delia 非常急,所以你只有 11 秒的時間。

由於這個結果可能過大,你只需要輸出總數模上 8011200280112002 的結果。

輸入格式
第一行,兩個正整數 n、mn、m,表示生物種類 nn 和喫與被喫的關係數 mm。

接下來 mm 行,每行兩個正整數,表示被喫的生物A和喫A的生物B。

輸出格式
一行一個整數,爲最大食物鏈數量模上 8011200280112002 的結果。

輸入輸出樣例
輸入 #1複製

5 7
1 2
1 3
2 3
3 5
2 5
4 5
3 4

輸出 #1複製

5

題意有點不好理解,就是最弱的到最強的有多少路。拓撲排序和記憶化搜索都可以寫。
拓撲排序

#include<cstdio> 
#include<queue>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=500005;
int inf=0x3f3f3f3f;
vector<int>v[maxn];
int vis[maxn],chu[maxn],ru[maxn],num,f[maxn],head[maxn*2];
int mod=80112002;
struct node{
	int to,next;
}s[maxn*2];
int read(){
	int f=1,sum=0;char ch=getchar();
	while(ch<'0'||ch>'9'){ if(ch=='-') f=-1; ch=getchar();}
	while(ch>='0'&&ch<='9') { sum=sum*10+ch-'0';ch=getchar();}
	return sum*f;
}
void add(int u,int v){
	s[++num]=(node){v,head[u]};
	head[u]=num;
}
int main()
{ 
	int n,m,i,j,k,t,w,x,y,c,ans=0;
	queue<int>q;
	scanf("%d %d",&n,&m);
	while(m--){
		x=read();y=read();
		chu[x]++;ru[y]++;
		add(x,y);
	}
	for(i=1;i<=n;i++)
		if(ru[i]==0){
			f[i]=1;
			q.push(i);
		}
	while(!q.empty()){
		t=q.front();
		q.pop();
		for(i=head[t];i;i=s[i].next){
			int to=s[i].to;
			f[to]+=f[t];
			f[to]%=mod;
			ru[to]--;
			if(!ru[to]){//可到達的數量計算完再入隊 
				if(!chu[to]){
					ans+=f[to];
					ans%=mod;
				} 
				else q.push(to);
			}
		}
	}
	printf("%d",ans);
    return 0;
}

dfs

#include<cstdio> 
#include<queue>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=500005;
int inf=0x3f3f3f3f;
vector<int>v[maxn];
int vis[maxn],a[maxn],b[maxn],num,c[maxn],head[maxn*2];
int mod=80112002;
struct node{
	int to,next;
}s[maxn*2];
int read(){
	int f=1,sum=0;char ch=getchar();
	while(ch<'0'||ch>'9'){ if(ch=='-') f=-1; ch=getchar();}
	while(ch>='0'&&ch<='9') { sum=sum*10+ch-'0';ch=getchar();}
	return sum*f;
}
void add(int u,int v){
	s[++num]=(node){v,head[u]};
	head[u]=num;
}
int dfs(int x){
	if(a[x]==0) return 1;
	if(c[x]) return c[x];
	long long sum=0;
	for(int i=head[x];i;i=s[i].next){
		sum=(sum+dfs(s[i].to))%mod;
	}
	c[x]=sum%mod;
	return c[x];
}
int main()
{ 
	int n,m,i,j,k,t,w,x,y,c;
	scanf("%d %d",&n,&m);
	while(m--){
		x=read();y=read();
		a[x]=1;b[y]=1;
		add(x,y);
	}
	long long ans=0;
	for(i=1;i<=n;i++){
		if(!b[i]){
			ans=(ans+dfs(i))%mod;
		}
	}
	printf("%d",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章