Code Festival B Union Find by kazsw

$_ = <>;
($n,$m) = split / /;
@tree=();
@rank=();
for($i=1;$i<=$n;$i++){
\x09$tree[$i] = $i;
\x09$rank[$i] = 0;
}
while($m--){
\x09$_ = <>;
\x09@d = split / /;
\x09if($d[0] == 0){
\x09\x09$a = find($d[1]);
\x09\x09$b = find($d[2]);
\x09\x09if($rank[$a]>$rank[$b]){
\x09\x09\x09$tree[$b] = $a;
\x09\x09}else{
\x09\x09\x09$tree[$a] = $b;
\x09\x09\x09if($rank[$a]==$rank[$b]){
\x09\x09\x09\x09$rank[$b]++;
\x09\x09\x09}
\x09\x09}
\x09}else{
\x09\x09print find($d[1])==find($d[2]) ? "YES":"NO","\n";
\x09}
}
sub find{$_=pop;$tree[$_]!=$_?$tree[$_]=find($tree[$_]):$_}

Note that non-ascii characters in the above source code will be escaped (such as \x9f).

download

return to the top page