洛谷P3183食物链-题解
原题:

思路:
可以采取类似于树形DP的做法
计算出从各个儿子到达目标点的方法
然后加起来,就是这个点的方法
就像是反向的计数DP
代码:
#include <bits/stdc++.h>
using namespace std;
struct node
{
int u,w,nxt;
}e[200010];
int st[100010],out[100010],ind[100010],f[100010],n,m,tot;
int ans;
void add(int x,int y)
{
e[++tot].u=x;
e[tot].w=y;
e[tot].nxt=st[x];
st[x]=tot;
}
int dfs(int x)
{
if(f[x])
return f[x];
int ans1=0;
if(out[x]==0)
return 1;
for(int i=st[x];i;i=e[i].nxt)
{
ans1+=dfs(e[i].w);
}
f[x]=ans1;
return ans1;
}
int main()
{
cin >> n >> m;
for(int j=1;j<=m;j++)
{
int a,b;
cin >> a >> b;
add(a,b);
ind[b]++;
out[a]++;
}
for (int i=1;i<=n;i++)
if (ind[i]==0 && out[i]!=0)
ans+=dfs(i);
cout << ans << endl;
return 0;
}
浙公网安备 33010602011771号