LCA - 2#3299

LCA - 2 (Editorial)

The problem requires implementing queries for finding the Lowest Common Ancestor (LCA) of pairs of vertices. The tree is given and remains unchanged during all queries. We’ll use the binary lifting algorithm.

Algorithm implementation

Declare the working arrays used in the binary lifting algorithm.

#define MAX 100010
#define LOGMAX 18
vector<int> g[MAX];
int d[MAX], f[MAX];
int up[MAX][LOGMAX];

The dfs function performs a depth-first traversal of the tree starting from vertex and constructs the ancestor table using the binary lifting method.

void dfs (int v, int p = 0, int len = 0) 
{
  d[v] = timer++;

  up[v][0] = p;
  for (int i = 1; i <= l; i++)
    up[v][i] = up[up[v][i-1]][i-1];

  for (int to : g[v])
    if (to != p) dfs (to, v, len + 1);

  f[v] = timer++;
}

The Parent function checks whether vertex is an ancestor of vertex .

int Parent(int a, int b)
{
  return (d[a] <= d[b]) && (f[a] >= f[b]);
}

The LCA function computes the Lowest Common Ancestor of vertices and .

int LCA (int a, int b) 
{
  if (Parent(a, b)) return a;
  if (Parent(b, a)) return b;
  for (int i = l; i >= 0; i--)
    if (!Parent(up[a][i], b)) a = up[a][i];
  return up[a][0];
}

The main part of the program. Read the input data.

scanf("%d %d",&n,&m);

Find the minimum value such that 2^l > n.

l = 1;
while ((1 << l) <= n)  l++;

Read the data and construct the tree.

for (i = 1; i <= n - 1; i++)
{
  scanf("%d",&v);
  g[v].push_back(i);
  g[i].push_back(v);
}

Run a depth-first search, during which the data structure required for the binary lifting algorithm is built.

timer = 0;
dfs(0);

Read the data needed to generate the queries.

scanf("%d %d",&a1,&a2);
scanf("%lld %lld %lld",&x,&y,&z);

Generate the queries, process them sequentially, and compute the required sum.

v = sum = 0;
for (i = 0; i < m; i++)
{
  v = LCA((a1 + v) % n, a2);
  sum += v;
  a1 = (x * a1 + y * a2 + z) % n;
  a2 = (x * a2 + y * a1 + z) % n;
}

Print the answer.

printf("%lld\n",sum);