Sunday, 28 June 2015

DSU implementation by blue mary


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 ( parent [ r o o t ] >= 0 )
r o o t = p a ren t [ r o o t ] ;
// p a t h compress ion
 while ( x ! = r o o t )
{ int ol d = x ;
x = p a ren t [ x ] ;
 p a ren t [ ol d ] = r o o t ;
 }
return r o o t ;
}
 /∗ Combines t h e s e t s t h a t x and y occupy . Re turns t r u e on ∗ s u c c e s s , or f a l s e i f x and y are a l r e a d y in 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 = f i n d ( x ) ;
 y = f i n d ( y ) ;
 // c heck f o r no−op
i f ( x == y ) return f a l s e ;
 // make s u re t h a t x i s t h e l a r g e r s e t . p a re n t [ x ] i s t h e // neg a te 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 ( paren t [ x ] > p a ren t [ y ] )
 swap ( x , y ) ;
// u p d a te t h e s i z e o f x
p a ren t [ x] += p a ren t [ y ] ;
 // p l a c e y under x p a ren t [ y ] = x ;
return true
; }

http://olympiad.cs.uct.ac.za/presentations/camp1_2006/unionfind-handout.pdf 

No comments:

Post a Comment