tarjan算法代码

耗费了大量的时间,很努力的去看,但是还是看不懂,水平依旧太低……

program Tarjan;



type

 atp=record

  x,y,next:longint;

 end;



var

 i,m,n,x,y,num,sum,DFN:longint;

 flag:array [1..10000] of boolean;

 low,index,ans,stack:array [1..10000] of longint;

 map:array [1..100000] of atp;

 

procedure work(v:longint);

var

 temp,temp1:longint;

begin



 inc(DFN);

 temp:=index[v];

 temp1:=DFN;

 low[v]:=DFN;

 while temp<>-1 do

  begin

   if flag[map[temp].y] then

    begin

     inc(num);

     stack[num]:=map[temp].y;

     flag[map[temp].y]:=false;

     work(map[temp].y);

     if low[v]>low[map[temp].y] then low[v]:=low[map[temp].y];     

    end

   else if ans[map[temp].y]=-1 then if low[v]>low[map[temp].y] then low[v]:=low[map[temp].y];

   temp:=map[temp].next;

  end;

  

 if low[v]=temp1 then 

  begin

   inc(sum);

   while stack[num+1]<>v do

    begin

     ans[stack[num]]:=sum;

     dec(num);

    end;

  end;

  

end;



begin

 assign(input,'tarjan.in'); reset(input);

 assign(output,'tarjan.out'); rewrite(output);

 

 readln(m,n);

 for i:=1 to n do index[i]:=-1;

 for i:=1 to m do 

  begin

   readln(x,y);

   map[i].x:=x;

   map[i].y:=y;

   map[i].next:=index[x];

   index[x]:=i;

  end;

  

 sum:=0;

 for i:=1 to n do 

  begin

   ans[i]:=-1;

   flag[i]:=true;

  end;

 for i:=1 to n do 

  begin

   if ans[i]=-1 then

    begin

     num:=1;

     DFN:=0;

     stack[1]:=i;

     work(i);

    end;

  end;

  

 for i:=1 to n do write(ans[i],' ');

 

 close(input); close(output);

end.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值