LCA(Tarjan)

program LCA(Tarjan);
type arr=record
     u,v,w,next:longint;
     end;
const maxn=100008;
      maxm=100008;
var eg:array[0..maxm*4] of arr;
    last,lasq,ans,fa:array[0..maxn] of longint;
    flag:array[0..maxn] of boolean;
    n,i,j,q,x,y:longint;
procedure add(u,v:longint);
begin
  inc(j);
  eg[j].u:=u;
  eg[j].v:=v;
  eg[j].next:=last[u];
  last[u]:=j;
end;
procedure adt(u,v,w:longint);
begin
  inc(j);
  eg[j].u:=u;
  eg[j].v:=v;
  eg[j].w:=w;
  eg[j].next:=last[u];
  lasq[u]:=j;
end;
function find(x:longint):longint;
begin
  if fa[x]=x then exit(x);
  fa[x]:=find(fa[x]);
  exit(fa[x]);
end;
procedure lca(u:longint);
var v,i:longint;
begin
  i:=last[u];
  while i<>-1 do
    begin
      v:=eg[i].v;
      if not flag[v] then
        begin
          flag[v]:=true;
          lca(v); fa[v]:=u;
        end;    
      i:=eg[i].next;
    end;
  i:=lasq[u];
  while i<>-1 do
    begin
      v:=eg[i].v;
      if flag[v] and (ans[eg[i].w]=-1) then
        ans[eg[i].w]:=find(v);
      i:=eg[i].next;    
    end;
end;
begin
  for i:=1 to maxn do begin last[i]:=-1; lasq[i]:=-1; end;
  j:=-1;
  readln(n,q);
 for i:=1 to n-1 do
    begin
      readln(x,y);
      add(x,y);
      add(y,x);
    end;
  for i:=1 to q do
    begin
      readln(x,y);
      adt(x,y,i);
      adt(y,x,i);
      ans[i]:=-1;
    end;
  fillchar(flag,sizeof(flag),false);
  for i:=1 to n do fa[i]:=i;
  flag[1]:=true;
  lca(1);
  for i:=1 to q do writeln(ans[i]);
end.

 

posted @ 2014-12-10 19:48  rpSebastian  阅读(284)  评论(0编辑  收藏  举报