Description
每一头牛的愿望就是变成一头最受欢迎的牛。现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎。 这种关系是具有传递性的,如果A认为B受欢迎,B认为C受欢迎,那么牛A也认为牛C受欢迎。你的任务是求出有多少头牛被所有的牛认为是受欢迎的。
Input
第一行两个数N,M。 接下来M行,每行两个数A,B,意思是A认为B是受欢迎的(给出的信息有可能重复,即有可能出现多个A,B)
Output
一个数,即有多少头牛被所有的牛认为是受欢迎的。
Sample Input
3 3
1 2
2 1
2 3
1 2
2 1
2 3
Sample Output
1
HINT
100%的数据N<=10000,M<=50000
求出强连通分量后缩点,考虑出度为0的点,如果只有一个,则这个点即为所求(因为已经缩点了,不会有环,其他点总能到达这个点)。否则没有(因为这些点之间是不可达的)。
type data=record
da,ne:longint;
end;
var
fi,la,pre,low,z,f,num:array[1..10000]of longint;
vis,cd:array[1..10000]of boolean;
a:array[1..50000]of data;
n,m,i,j,k,t,time,top,c:longint;
procedure dfs(i:longint);
var j,k:longint;
begin
inc(time);
low[i]:=time; pre[i]:=time;
vis[i]:=true;
inc(top); z[top]:=i;
k:=fi[i];
while k<>0 do
begin
j:=a[k].da;
if f[j]=0 then
begin
if vis[j]=false then dfs(j);
if low[j]<low[i] then low[i]:=low[j];
end;
k:=a[k].ne;
end;
if low[i]=pre[i] then
begin
inc(c);
while z[top]<>i do
begin
f[z[top]]:=c;
dec(top);
inc(num[c]);
end;
f[i]:=c;
dec(top);
inc(num[c]);
end;
end;
begin
readln(n,m);
for k:=1 to m do
begin
readln(i,j);
inc(t);
if fi[i]=0 then
begin
fi[i]:=t;
la[i]:=t;
a[t].da:=j;
end else
begin
a[la[i]].ne:=t;
la[i]:=t;
a[t].da:=j;
end;
end;
for i:=1 to n do
if vis[i]=false then dfs(i);
for i:=1 to n do
begin
k:=fi[i];
while k<>0 do
begin
j:=a[k].da;
if f[i]<>f[j] then cd[f[i]]:=true;
k:=a[k].ne;
end;
end;
j:=0; k:=0;
for i:=1 to c do
if cd[i]=false then
begin
inc(j);
k:=k+num[i];
end;
if j>1 then writeln('0')
else writeln(k);
end.