Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Union-nd algorithms Sample code

Bruce Merry March 2, 2006

/ Returns a node t h a t i s i n t h e same s e t as x . The same node w i l l be r e t u r n e d f o r any x i n t h e same s e t . / int f i n d ( int x ) { // i d e n t i f y t h e r o o t int r o o t = x ; while ( p a r e n t [ r o o t ] > = 0 ) r o o t = p a r e n t [ r o o t ] ; // p a t h c o m p r e s s i o n while ( x ! = r o o t ) { int o l d = x ; x = parent [ x ] ; parent [ old ] = root ; } return r o o t ; } / Combines t h e s e t s t h a t x and y occupy . Returns t r u e on s u c c e s s , or f a l s e i f x and y a r e a l r e a d y i n t h e same s e t . / bool merge ( int x , int y ) { // i d e n t i f y r o o t s x = find (x ); y = find (y ); // c h e c k f o r noop i f ( x == y ) return f a l s e ; // make s u r e t h a t x i s t h e l a r g e r s e t . p a r e n t [ x ] i s t h e // n e g a t e d s i z e o f t h e s e t c o n t a i n i n g x . i f ( p a r e n t [ x ] > p a r e n t [ y ] ) swap ( x , y ) ; // u p d a t e t h e s i z e o f x p a r e n t [ x ] += p a r e n t [ y ] ; // p l a c e y under x parent [ y ] = x ; return true ; }

You might also like