pku1330 Nearest Common Ancestors
裸的求最近公共祖先,LCA-->RMQ,没什么大问题,只不过标号不再完美,需要在深度序列中找最小值,最后再对应回去。
View Code
1 rogram pku1330(input,output); 2 type 3 node = ^link; 4 link = record 5 goal : longint; 6 next : node; 7 end; 8 var 9 tree : array[0..31000] of node; 10 eurl : array[0..30000] of longint; 11 depth : array[0..30000] of longint; 12 pos : array[0..31000] of longint; 13 f : array[0..21000,0..20] of longint; 14 v : array[0..11000] of boolean; 15 root : longint; 16 n,tot : longint; 17 i,cases : longint; 18 function max(aa,bb: longint ):longint; 19 begin 20 if aa>bb then 21 exit(aa); 22 exit(bb); 23 end; { max } 24 function min(aa,bb : longint ):longint; 25 begin 26 if aa<bb then 27 exit(aa); 28 exit(bb); 29 end; { min } 30 procedure add(xx,yy :longint ); 31 var 32 tt : node; 33 begin 34 new(tt); 35 tt^.goal:=yy; 36 tt^.next:=tree[xx]; 37 tree[xx]:=tt; 38 end; { add } 39 procedure delete(); 40 var 41 tt : node; 42 begin 43 for i:=1 to n do 44 while tree[i]<>nil do 45 begin 46 tt:=tree[i]; 47 tree[i]:=tt^.next; 48 dispose(tt); 49 end; 50 end; { delete } 51 procedure init; 52 var 53 i,xx,yy : longint; 54 begin 55 readln(n); 56 fillchar(v,sizeof(v),false); 57 for i:=1 to n-1 do 58 begin 59 readln(xx,yy); 60 add(xx,yy); 61 v[yy]:=true; 62 end; 63 for i:=1 to n do 64 if not v[i] then 65 begin 66 root:=i; 67 break; 68 end; 69 for i:=1 to n do 70 pos[i]:=-1; 71 tot:=0; 72 end; { init } 73 procedure dfs(now,dep :longint ); 74 var 75 t : node; 76 begin 77 inc(tot); 78 eurl[tot]:=now; 79 depth[tot]:=dep; 80 if pos[now]=-1 then 81 pos[now]:=tot; 82 t:=tree[now]; 83 while t<>nil do 84 begin 85 dfs(t^.goal,dep+1); 86 inc(tot); 87 eurl[tot]:=now; 88 depth[tot]:=dep; 89 t:=t^.next; 90 end; 91 end; { dfs } 92 procedure Sparse_Table(); 93 var 94 i,j : longint; 95 begin 96 for i:=1 to tot do 97 f[i,0]:=i; 98 for j:=1 to trunc(ln(tot)/ln(2)) do 99 for i:=1 to tot do 100 if i+1<<(j-1)>tot then 101 break 102 else 103 begin 104 if depth[f[i,j-1]]<depth[f[i+1<<(j-1),j-1]] then 105 f[i,j]:=f[i,j-1] 106 else 107 f[i,j]:=f[i+1<<(j-1),j-1]; 108 end; 109 end; { Sparse_Table } 110 procedure solve(); 111 var 112 x,y,t,xx,yy : longint; 113 begin 114 readln(x,y); 115 xx:=pos[x]; 116 yy:=pos[y]; 117 x:=min(xx,yy); 118 y:=max(xx,yy); 119 t:=trunc(ln(y-x+1)/ln(2)); 120 if depth[f[x,t]]<depth[f[y-1<<t+1,t]] then 121 writeln(eurl[f[x,t]]) 122 else 123 writeln(eurl[f[y-1<<t+1,t]]); 124 end; { solve } 125 begin 126 for i:=1 to 10001 do 127 tree[i]:=nil; 128 readln(cases); 129 while cases>0 do 130 begin 131 dec(cases); 132 delete(); 133 init; 134 dfs(root,0); 135 Sparse_Table(); 136 solve(); 137 end; 138 end.