[BZOJ3282/LGOJ3690] Link-Cut Tree 模板題

原題鏈接

Link-Cut Tree模板題

沒什麼解釋

先存個檔....

{Beginner_df016}
var i,j,k,n,m,top,x,y,id:longint;
    s,v,fa,q,rev:array[0..300007]of longint;
	c:array[0..300007,0..2]of longint;
procedure swap(var a,b:longint);
var t:longint;
begin
  t:=a; a:=b; b:=t;
end;
procedure update(x:longint);
var l,r:longint;
begin
  l:=c[x][0]; r:=c[x][1];
  s[x]:=s[l] xor s[r] xor v[x];
end;
procedure pushdown(x:longint);
var l,r:longint;
begin
  l:=c[x][0]; r:=c[x][1];
  if rev[x]<>0 then
   begin
   rev[x]:=rev[x] xor 1;
   rev[l]:=rev[l] xor 1;
   rev[r]:=rev[r] xor 1;
   swap(c[x][0],c[x][1]);
   end;
end;
function isroot(x:longint):longint;//判斷x是否爲所在Auxiliary tree的根節點
var p:boolean;
begin
  p:=(c[fa[x]][0]<>x) and (c[fa[x]][1]<>x);
  exit(ord(p));
end;
procedure rotate(x:longint);
var y,z,l,r:longint;
begin
  y:=fa[x]; z:=fa[y];
  if (c[y][0]=x)then l:=0 else l:=1;
  r:=l xor 1;
  if isroot(y)=0 then
   if c[z][0]=y then c[z][0]:=x else c[z][1]:=x;
  fa[x]:=z; fa[y]:=x; fa[c[x][r]]:=y;
  c[y][l]:=c[x][r]; c[x][r]:=y;
  update(y); update(x);
end;
procedure splay(x:longint);
var i,y,z:longint;
begin
  top:=0;
  inc(top); q[top]:=x;
  i:=x;
  while isroot(i)=0 do
   begin
   inc(top); q[top]:=fa[i];
   i:=fa[i];
   end;
  for i:=top downto 1 do pushdown(q[i]);
  while isroot(x)=0 do
   begin
   y:=fa[x]; z:=fa[y];
   if isroot(y)=0 then
    if (c[y][0]=x)xor(c[z][0]=y)
	 then rotate(x) else rotate(y);
   rotate(x);
   end;
end;
procedure access(x:longint);//打通LCT根節點到x的Preferred Path
var t:longint;
begin
  t:=0;
  while x<>0 do
   begin
   splay(x);
   c[x][1]:=t;
   update(x);
   t:=x;
   x:=fa[x];
   end;
end;
procedure makeroot(x:longint);//將x變爲所在Auxiliary tree的根節點
begin
  access(x);
  splay(x);
  rev[x]:=rev[x] xor 1;
end;
function find(x:longint):longint;//查詢x所在Auxiliary tree的根節點
begin
  access(x); splay(x);
  while c[x][0]<>0 do x:=c[x][0];
  exit(x);
end;
procedure cut(x,y:longint);//將x和y斷開
begin
  makeroot(x);
  access(y);
  splay(y);
  if c[y][0]=x then begin c[y][0]:=0; fa[x]:=0; end;
end;
procedure link(x,y:longint);//將x賦值爲y
begin
  makeroot(x);
  fa[x]:=y;
end;
begin
  readln(n,m);
  for i:=1 to n do readln(v[i]);
  for i:=1 to n do s[i]:=v[i];
	
  for i:=1 to m do
   begin
   readln(id,x,y);
   if id=0 then begin makeroot(x); access(y); splay(y); writeln(s[y]); continue; end;
   if id=1 then begin if find(x)<>find(y) then link(x,y); continue; end;
   if id=2 then begin if find(x)=find(y) then cut(x,y); continue; end;
   if id=3 then begin access(x); splay(x); v[x]:=y; update(x); continue; end;
   end;
end.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章