Codevs1036 商务旅行 LCA【pascal】

LCA模板题,注意是双向边=。=,而且是顺次经过m个城市

var
        n,a,b,l,m,ans     :longint;
        i,j               :longint;
        vis               :array[0..30010] of boolean;
        last,d            :array[0..30010] of longint;
        pre,other         :array[0..60010] of longint;
        jump              :array[0..30010,0..20] of longint;
procedure connect(x,y:longint);
begin
   inc(l);
   pre[l]:=last[x];
   last[x]:=l;
   other[l]:=y;
end;

procedure dfs(x:longint);
var
        p,q:longint;
begin
   q:=last[x];
   while (q<>0) do
   begin
      p:=other[q];
      if not vis[p] then
      begin
         vis[p]:=true;
         jump[p,0]:=x;
         d[p]:=d[x]+1;
         dfs(p);
      end;
      q:=pre[q];
   end;
end;

procedure swap(var a,b:longint);
var
        c:longint;
begin
   c:=a;a:=b;b:=c;
end;

procedure lca(x,y:longint);
var
        p,q:longint;
        i,j:longint;
begin
   if (d[x]<d[y]) then swap(x,y);
   for i:=0 to 15 do
    if ((d[x]-d[y]) and (1<<i)<>0) then
    begin
       inc(ans,1<<i);
       x:=jump[x,i];
    end;
   if (x<>y) then
   begin
      for i:=15 downto 0 do
       if (jump[x,i]<>jump[y,i]) then
       begin
          inc(ans,2*(1<<i));
          x:=jump[x,i];
          y:=jump[y,i];
       end;
      inc(ans,2);
   end;
end;


begin
   read(n);
   for i:=1 to n-1 do
   begin
      read(a,b);
      connect(a,b);
      connect(b,a);
   end;
   d[1]:=1;vis[1]:=true;dfs(1);
   for j:=1 to 15 do
    for i:=1 to n do jump[i,j]:=jump[jump[i,j-1],j-1];
   read(m);
   read(a);
   for i:=1 to m-1 do
   begin
      read(b);
      lca(a,b);
      a:=b;
   end;
   writeln(ans);
end.
——by  Eirlys

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值