【题意】: 很简单,数一张食物网中的食物链个数。
【思路】:
直接建图,统计每个点
i
i
i的入度
i
n
d
i
ind_i
indi和出度
o
u
t
i
out_i
outi
记
f
i
f_i
fi为以
i
i
i为起点的食物链的个数,显然任何时候
f
i
f_i
fi都是一样的,据此,我们可以利用记忆化搜索来求
f
i
f_i
fi,这样可以大大降低搜索的时间复杂度,从而避免
T
L
E
TLE
TLE
如何搜索?
我们从一个顶级消费者(即
i
n
d
i
=
0
ind_i=0
indi=0且
o
u
t
i
≠
0
out_i \neq 0
outi=0的点)开始搜索,直到一个生产者(即
o
u
t
i
=
=
0
out_i==0
outi==0且
i
n
d
i
≠
0
ind_i \neq 0
indi=0的点)结束
当然,对于分解者(
i
n
d
i
=
o
u
t
i
=
0
ind_i=out_i=0
indi=outi=0的点)不能进行搜索
注意,答案可能要用
l
o
n
g
long
long
l
o
n
g
long
long
【代码】:
//By HPXXZYY
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define gc getchar()
#define g(c) isdigit(c)
inline int read(){
char c=0;int x=0;bool f=0;
while (!g(c)) f=c=='-',c=gc;
while (g(c)) x=x*10+c-48,c=gc;
return f?-x:x;
}
const int N=100100;
int ind[N],out[N];
long long f[N],ans;
struct node{
int next,to;
}e[N<<1];int h[N],tot;
inline void add(int a,int b){
e[++tot]=(node){h[a],b};
h[a]=tot;out[a]++;ind[b]++;
}
long long dfs(int u){
if (out[u]==0) return 1;
if (f[u]>0) return f[u];
for(int i=h[u];i;i=e[i].next){
register int to=e[i].to;
f[u]+=dfs(to);
}
return f[u];
}
int n,m,i,x,y;
int main(){
n=read();m=read();
for(i=1;i<=m;i++){
x=read();
y=read();
add(x,y);
}
for(i=1;i<=n;i++)
if (out[i]&&!ind[i])
ans+=dfs(i);
cout<<ans;
return 0;
}