Skip to content

Instantly share code, notes, and snippets.

@luccasiau
Created May 10, 2015 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luccasiau/4d95e21f40586c078497 to your computer and use it in GitHub Desktop.
Save luccasiau/4d95e21f40586c078497 to your computer and use it in GitHub Desktop.
int LCA(int u, int v){
if(nivel[u] < nivel[v]) swap(u, v); // isto é para definir u como estando mais abaixo
// vamos agora fazer nivel[u] ser
// igual nivel[v], subindo pelos
// ancestrais de u
for(int i = MAXL-1;i >= 0;i--)
if(nivel[u] - (1<<i) >= nivel[v])
u = ancestral[u][i];
// agora, u e v estão no mesmo nível
if(u == v) return u;
// subimos o máximo possível de forma
// que os dois NÃO passem a ser iguais
for(int i = MAXL-1;i >= 0;i--)
if(ancestral[u][i] != -1 && ancestral[u][i] != ancestral[v][i]){
u = ancestral[u][i];
v = ancestral[v][i]
}
// como subimos o máximo possível
// sabemos que u != v e que pai[u] == pai[v]
// logo, LCA(u, v) == pai[u] == pai[v]
return ancestral[u][0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment