-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnionFind.cpp
44 lines (38 loc) · 998 Bytes
/
UnionFind.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "UnionFind.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int UnionFind::find( int index ){
if( index >= size )
return -1;
if( this->parents[index] != index ){
this->parents[index] = this->find( this->parents[index] );
return this->parents[index];
}
return index;
}
bool UnionFind::merge( int i, int j ){
int a = find( i ), b = find(j);
// if we have invalid arguments
if( a == -1 || b == -1 ) return -1;
if( a == b ) return false;
if( this->weights[a] > this->weights[b] ) this->parents[b] = a;
else if( this->weights[a] < this->weights[b] ) this->parents[a] = b;
if( this->weights[a] == this->weights[b] ){
this->parents[a] = b;
this->weights[b]++;
}
// printf("%d\n", this->groups );
this->groups = this->groups-1;
// printf("%d\n", this->groups );
// char c; scanf("%d", &c );
return true;
}
int UnionFind::getGroups(){
return this->groups;
}
void UnionFind::clear(){
free( this->weights );
free( this->parents );
}