mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-14 10:50:13 +08:00
formatting source-code for d7af6fdc8c
This commit is contained in:
@@ -10,16 +10,16 @@ const int LG = log2(N) + 1;
|
||||
struct lca
|
||||
{
|
||||
int n;
|
||||
vector<int> adj[N]; // Graph
|
||||
int up[LG][N]; // build this table
|
||||
int level[N]; // get the levels of all of them
|
||||
vector<int> adj[N]; // Graph
|
||||
int up[LG][N]; // build this table
|
||||
int level[N]; // get the levels of all of them
|
||||
|
||||
lca(int n_): n(n_)
|
||||
lca(int n_) : n(n_)
|
||||
{
|
||||
memset(up, -1, sizeof(up));
|
||||
memset(level, 0, sizeof(level));
|
||||
for (int i = 0; i < n - 1; ++i)
|
||||
{
|
||||
{
|
||||
int a, b;
|
||||
cin >> a >> b;
|
||||
a--;
|
||||
@@ -34,15 +34,15 @@ struct lca
|
||||
void verify()
|
||||
{
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
{
|
||||
cout << i << " : level: " << level[i] << endl;
|
||||
}
|
||||
cout << endl;
|
||||
for (int i = 0; i < LG; ++i)
|
||||
{
|
||||
{
|
||||
cout << "Power:" << i << ": ";
|
||||
for (int j = 0; j < n; ++j)
|
||||
{
|
||||
{
|
||||
cout << up[i][j] << " ";
|
||||
}
|
||||
cout << endl;
|
||||
@@ -52,11 +52,11 @@ struct lca
|
||||
void build()
|
||||
{
|
||||
for (int i = 1; i < LG; ++i)
|
||||
{
|
||||
{
|
||||
for (int j = 0; j < n; ++j)
|
||||
{
|
||||
{
|
||||
if (up[i - 1][j] != -1)
|
||||
{
|
||||
{
|
||||
up[i][j] = up[i - 1][up[i - 1][j]];
|
||||
}
|
||||
}
|
||||
@@ -66,10 +66,10 @@ struct lca
|
||||
void dfs(int node, int par)
|
||||
{
|
||||
up[0][node] = par;
|
||||
for (auto i: adj[node])
|
||||
{
|
||||
for (auto i : adj[node])
|
||||
{
|
||||
if (i != par)
|
||||
{
|
||||
{
|
||||
level[i] = level[node] + 1;
|
||||
dfs(i, node);
|
||||
}
|
||||
@@ -80,28 +80,28 @@ struct lca
|
||||
u--;
|
||||
v--;
|
||||
if (level[v] > level[u])
|
||||
{
|
||||
{
|
||||
swap(u, v);
|
||||
}
|
||||
// u is at the bottom.
|
||||
int dist = level[u] - level[v];
|
||||
// Go up this much distance
|
||||
for (int i = LG - 1; i >= 0; --i)
|
||||
{
|
||||
{
|
||||
if (dist & (1 << i))
|
||||
{
|
||||
{
|
||||
u = up[i][u];
|
||||
}
|
||||
}
|
||||
if (u == v)
|
||||
{
|
||||
{
|
||||
return u;
|
||||
}
|
||||
assert(level[u] == level[v]);
|
||||
for (int i = LG - 1; i >= 0; --i)
|
||||
{
|
||||
{
|
||||
if (up[i][u] != up[i][v])
|
||||
{
|
||||
{
|
||||
u = up[i][u];
|
||||
v = up[i][v];
|
||||
}
|
||||
@@ -113,8 +113,8 @@ struct lca
|
||||
|
||||
int main()
|
||||
{
|
||||
int n; // number of nodes in the tree.
|
||||
lca l(n); // will take the input in the format given
|
||||
int n; // number of nodes in the tree.
|
||||
lca l(n); // will take the input in the format given
|
||||
// n-1 edges of the form
|
||||
// a b
|
||||
// Use verify function to see.
|
||||
|
||||
Reference in New Issue
Block a user