poj2186 Popular Cows

来源:互联网 发布:干软件二次开发怎么样 编辑:程序博客网 时间:2024/05/17 14:20

Description

Every cow's dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is 
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow. 

Input

* Line 1: Two space-separated integers, N and M 

* Lines 2..1+M: Two space-separated numbers A and B, meaning that A thinks B is popular. 

Output

* Line 1: A single integer that is the number of cows who are considered popular by every other cow. 
题解:
首先用Tarjan求出联通分量的个数,然后依次求各个联通分量的出度,如果仅有一个连通分量出度为0则这个联通分量内的点的个数就是答案;如果有多于一个的联通分量的出度为0,则说明此有向图肯定不连通。因此直接输出0。
代码:
procedure dfs(k:longint);  
  var  
    tmp:longint;  
  begin  
    inc(d);  
    l[k]:=d; 
    f1[k]:=d; 
    v[k]:=true;  
    inc(t);  
    s[t]:=k; f[k]:=true;  
    temp:=h[k];  
    while temp<>-1 do  
    begin  
      if v[e[temp].t]=false then  
      begin  
        dfs(e[temp].t);  
        l[k]:=min(l[k],l[e[temp].t]);  
      end  
      else  
        if f[e[temp].t] then l[k]:=min(l[k],f1[e[temp].t]);  
      temp:=e[temp].next;  
    end;  
    if f1[k]=l[k] then begin inc(ans); main(k); end;  
  end;  
3 0
原创粉丝点击