5166. 卢学魔
Description
Input
Output
Sample Input
10 16
1 2
1 4
1 10
2 3
2 5
4 3
4 5
4 8
6 5
7 6
7 9
8 5
9 8
10 6
10 7
10 9
Sample Output
9
Data Constraint
Hint
分析:记忆化dfs一下。
代码
#include <cstdio>
#define N 500000
using namespace std;
struct arr
{
int to,nxt;
}a[N];
int l,ls[N],in[N],out[N];
int ans,n,m,f[N];
void add(int x, int y)
{
a[++l].to = y;
a[l].nxt = ls[x];
ls[x] = l;
}
void dfs(int x)
{
if (f[x])
{
ans+=f[x];
return;
}
if (!out[x])
{
ans++;
f[x]++;
return;
}
for (int i = ls[x]; i; i = a[i].nxt)
{
dfs(a[i].to);
f[x]+=f[a[i].to];
}
}
int main()
{
scanf("%d%d", &n ,&m);
for (int i = 1; i <= m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
add(x, y);
out[x]++;
in[y]++;
}
for (int i = 1; i <= n; i++)
if (!in[i] && out[i]) dfs(i);
printf("%d", ans);
}