File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed
Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+ public class QuickFindUF
3+ {
4+ private int id [];
5+ public QuickFindUF (int N )
6+ {
7+ id =new int [N ];
8+ }
9+ public boolean connected (int p ,int q )
10+ {
11+ return id [p ]==id [q ];
12+ }
13+ public void union (int p ,int q )
14+ {
15+ int pid =id [p ];
16+ int qid =id [q ];
17+ for (int i =0 ;i <id .length ;i ++)
18+ {
19+ if (id [i ]==pid )
20+ id [i ]=qid ;
21+ }
22+ }
23+ }
Original file line number Diff line number Diff line change 1+ public class QuickUnionUF
2+ {
3+ private int [] id ;
4+
5+ public QuickUnionUF (int n )
6+ {
7+ id = new int [N ];
8+ for (int i =0 ;i <n ;i ++)
9+ {
10+ id [i ]=i ;
11+ }
12+ }
13+
14+ private int root (int i )
15+ {
16+ while (i != id [i ])
17+ {
18+ i =id [i ];
19+ }
20+ return i ;
21+ }
22+
23+ public boolean connected (int p ,int q )
24+ {
25+ return root (p )==root (q );
26+ }
27+
28+ public void union (int p ,int q )
29+ {
30+ int i = root (p );
31+ int j = root (q );
32+ id [i ] = j ;
33+ }
34+ }
You can’t perform that action at this time.
0 commit comments