Skip to content

Instantly share code, notes, and snippets.

@rogerioagjr
Created May 18, 2015 17:56
Show Gist options
  • Save rogerioagjr/17d9298fbc7123e5c3e2 to your computer and use it in GitHub Desktop.
Save rogerioagjr/17d9298fbc7123e5c3e2 to your computer and use it in GitHub Desktop.
Naïve Union-Find
#define MAXN 100100
int pai[MAXN]; // crio o vetor que armazenará os pais
// função find: retorna o patriarca de um elemento x
int find(int x){
// se ele for pai de si mesmo, ele é o patriarca
if(pai[x]==x) return x;
// se não, devo olhar o patriarca de seu pai
return find(pai[x]);
}
// função join: faz a união dos conjuntos dos elementos x e y
void join(int x, int y){
// basta fazer o patriarca de um se tornar pai do patriarca do outro
pai[find(x)]=find(y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment