还须加强递归的理解啊。。。 const maxn=30000; var n,i,x,y:longint; h:array[1..maxn] of longint;{队首} d:array[1..maxn] of longint;{距离队首的深度} t:array[1..maxn] of longint;{后面接着的个数} s:char; function findset(x:longint):longint; var hx:longint; begin if h[x]<>x then begin hx:=findset(h[x]); inc(d[x],d[h[x]]); h[x]:=hx; end; exit(h[x]); end; procedure union(x,y:longint); begin x:=findset(x); y:=findset(y); h[x]:=y; d[x]:=t[y]; t[y]:=t[y]+t[x]; end; procedure query(x,y:longint); begin if findset(x)<>findset(y) then writeln('-1') else writeln(abs(d[x]-d[y])-1); end; begin readln(n); for i:=1 to maxn do begin h[i]:=i; d[i]:=0; t[i]:=1; end; for i:=1 to n do begin read(s); readln(x,y); cases of 'M':union(x,y); 'C':query(x,y); end; end; end.
1540银河英雄传说{并查集}
最新推荐文章于 2022-10-30 22:24:58 发布