Popular Cows poj 2186 tarjan

题意/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. 


题解/solution

        先跑一遍taijian算法。那么出度为0的强连通分量代表的就是受其他奶牛欢迎的,但是如果出度为0的强连通分量的个数大于1.那么则无解。因为将至少有两个分量里的奶牛互相不喜欢。所以我们的算法就是如果出度为0的强连通分量的个数是1.那么我们算出这里面点的个数就是最后的答案。


代码/Code

const
  maxE=500001;
  maxV=50001;

type
  arr=record
        x,y,w,next:longint;
      end;
Var
  n,m,t,ans,t1:longint;
  tu:array [0..maxE] of arr;
  v:array [0..maxV] of Boolean;
  ls,a,ru,cu,low,dfn,f:array [0..maxV] of longint;
procedure dfs(o:longint);
Var
  i,j,k:longint;
begin
  inc(t);
  f[t]:=o;
  v[o]:=true;
  inc(t1);
  low[o]:=t1;
  dfn[o]:=t1;
  i:=ls[o];
  while i<>0 do
    with tu[i] do
      begin
        if dfn[y]=0 then
          begin
            dfs(y);
            if low[o]>low[y] then low[o]:=low[y];
          end else
            if (low[o]>dfn[y]) and (v[y]) then low[o]:=dfn[y];
        i:=next;
      end;
  if low[o]=dfn[o]then
    begin
      ans:=ans+1;
      repeat
        j:=f[t];
        t:=t-1;
        a[j]:=ans;
        v[j]:=false;
      until j=o;
    end;
end;

procedure init;
var
  i,k:longint;
begin
  readln(n,m);
  k:=0;
  ans:=0;
  for i:=1 to m do
    with tu[i] do
      begin
        readln(x,y);
        next:=ls[x];
        ls[x]:=i;
      end;
  for i:=1 to n do
    if a[i]=0 then dfs(i);
end;

procedure main;
var
  i,j:longint;
begin
  for i:=1 to n do
    begin
      j:=ls[i];
      while j<>0 do
        with tu[j] do
          begin
            if a[x]<>a[y]
              then
                begin
                  cu[a[x]]:=cu[a[x]]+1;
                  ru[a[y]]:=ru[a[y]]+1;
                end;
            j:=next;
          end;
    end;
end;

procedure print;
var
  i,o,k:longint;
begin
  k:=0;
  for i:=1 to ans do
    if cu[i]=0 then k:=k+1;
  if k<>1 then
    begin
      write(0);
      halt;
    end;
  k:=0;
  for i:=1 to ans do
    if cu[i]=0 then k:=i;
  o:=0;
  for i:=1 to n do
    if a[i]=k then o:=o+1;
  write(o);
end;

begin
  init;
  main;
  print;
end.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值