Kitty's Calculations on a Tree#11273

Kitty's Calculations on a Tree (Editorial)

Split each term u \cdot v \cdot \mathit{dist}(u, v) into \mathit{dist}(u, v) terms u \cdot v — one for each edge of the path between and . Then the required sum equals the sum over all edges of the tree of the value \sum u \cdot v, where the summation is over pairs of vertices of the set whose path passes through .

For example, for the set \{2, 4, 5\} from the third query, each pair is split along the edges of its path, and then the terms are collected by edges:

Contribution of an edge. Root the tree at vertex and consider an edge e = (p, x), where is the parent of . If the edge is removed, the tree splits into the subtree of vertex and the rest. The path between and passes through if and only if these vertices lie in different parts. Let be the sum of the numbers of all vertices of the set, and the sum of the numbers of the set vertices in the subtree of . Then the contribution of the edge equals

\sum u \cdot v = \mathit{sub}[x] \cdot (s - \mathit{sub}[x])

Iterating over all edges of the tree takes operations per set, and for q = 10^5 this is too slow. Note that only edges lying on paths between vertices of the set have a nonzero contribution. Moreover, on a chain of edges containing no branching of paths and no vertices of the set, the value does not change, so all edges of such a chain have the same contribution.

Compressed (virtual) tree. Keep only the vertices of the set and the pairwise LCAs of these vertices. Connect each vertex with its nearest ancestor from this set. An edge (\mathit{par}[x], x) of the compressed tree replaces a chain of \mathit{dist}[x] - \mathit{dist}[\mathit{par}[x]] edges of the original tree, and all of them have the contribution \mathit{sub}[x] \cdot (s - \mathit{sub}[x]). Therefore, the answer equals the sum

(\mathit{dist}[x] - \mathit{dist}[\mathit{par}[x]]) \cdot \mathit{sub}[x] \cdot (s - \mathit{sub}[x])

over all vertices of the compressed tree except its root. Here is the depth of vertex in the original tree.

Building the compressed tree. Put the vertices of the set into the list and sort them by the entry time of the depth-first search. We obtain the sequence \mathit{vt}[0], \mathit{vt}[1], \ldots, \mathit{vt}[k - 1], in which the vertices go in the order of their visit by the traversal. It is known that the set of pairwise LCAs of the set vertices coincides with the set of LCAs of vertices adjacent in this order. Therefore, it is enough to add to the list another k - 1 vertices \mathit{LCA}(\mathit{vt}[i], \mathit{vt}[i + 1]) for i = 0, 1, \ldots, k - 2, sort the list by entry time again, and remove duplicates. After that, contains all vertices of the compressed tree, there are at most 2k - 1 of them, and the first element is the root of the compressed tree.

The parent of each vertex is found using a stack. We iterate over the vertices of the list in order, keeping in the stack the path from the root of the compressed tree to the last processed vertex. While the top element of the stack is not an ancestor of the current vertex , we pop it. The remaining top element of the stack is . Then we push onto the stack.

The values are computed by iterating over the list from the end, that is, in decreasing order of entry time. Initially \mathit{sub}[x] = x for vertices of the set and \mathit{sub}[x] = 0 for the added LCA vertices. When vertex is reached, all its descendants in the compressed tree have already been processed, and each of them has added its value to the value of its parent. Therefore, at this moment equals the sum of the numbers of the set vertices in the whole subtree of .

We take into account the contribution of the edge (\mathit{par}[x], x). It replaces \mathit{dist}[x] - \mathit{dist}[\mathit{par}[x]] edges of the original tree, and each of them divides the vertices of the set into two parts: the subtree of with the sum of numbers and the remaining vertices with the sum s - \mathit{sub}[x]. Therefore, the contribution of the edge equals

(\mathit{dist}[x] - \mathit{dist}[\mathit{par}[x]]) \cdot \mathit{sub}[x] \cdot (s - \mathit{sub}[x])

After that, we add to . In this way the sum of the subtree of is passed upward: when vertex is reached, its value will account not only for itself, but also for with all its descendants. Exactly this value is needed for the contribution of the edge leading from to its parent. Each vertex passes its value only to its parent, so all values are computed in a single pass over the list .

For example, in the third set \{2, 4, 5\} the list \mathit{vt} = (1, 2, 5, 4) is processed from the end: vertices , , and in turn add , , and to , and finally \mathit{sub}[1] = 11 = s. The value of the root is not used: the root has no edge to a parent.

All computations are performed modulo 10^9 + 7.

Complexity. Preprocessing takes O(n \log n). A set of vertices is processed in O(k \log n): sorting and k - 1 LCA computations. The sum of all does not exceed 2 \cdot 10^5, so the total complexity is O((n + \sum k) \log n). The recursion depth of the traversal can reach n = 2 \cdot 10^5 if the tree is a chain.

Example

First set : \mathit{dist}(2, 4) = 2, the answer is 2 \cdot 4 \cdot 2 = 16. The second set consists of one vertex, the answer is .

Consider the third set \{2, 4, 5\} in detail, s = 2 + 4 + 5 = 11. The depth-first search from vertex visits the vertices in the order 1, 2, 3, 5, 6, 7, 4, so after sorting by entry time we get .

The lowest common ancestors of adjacent vertices: \mathit{LCA}(2, 5) = 1 and \mathit{LCA}(5, 4) = 1. After adding, sorting, and removing duplicates, the vertices of the compressed tree are 1, 2, 5, 4.

Find the parents using the stack:

Process the vertices in reverse order:

Answer: 28 + 60 + 18 = 106.

The left part shows the contribution of each edge of the original tree, the right part shows the compressed tree. The edge — of the compressed tree replaces the two edges — and — with the same contribution , so its contribution is multiplied by the length .

Algorithm Implementation

Declare the constants: is the size of the arrays, \mathit{MOD} = 10^9 + 7 is the modulus used for the answer.

#define MAX 200001
#define MOD 1000000007

Declare the global variables. The tree is stored in the adjacency list . The timestamps and are the entry and exit times of a vertex during the depth-first search, is the depth of vertex , and \mathit{up}[v][i] is the ancestor of vertex located 2^i levels higher. For the compressed tree we use the array — the parent of vertex , — a stack, — the sum of the numbers of the set vertices in the subtree of , and the list of vertices of the compressed tree.

vector<int> g[MAX];
int timer, d[MAX], f[MAX], dist[MAX];
int up[MAX][20];
int par[MAX];
long long sub[MAX];
vector<int> vt;
stack<int> st;

The dfs function performs a depth-first search from vertex . The parameter is the parent of vertex , and is its depth. On entering the vertex, we record its entry time, its immediate parent, and its depth. The root is considered to be its own parent.

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

Fill the row of the binary lifting table for vertex : the ancestor 2^i levels higher is the ancestor 2^{i-1} levels higher of the ancestor 2^{i-1} levels higher.

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

Run the traversal from all children of vertex , and then record the exit time .

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

The Parent function returns true if vertex is an ancestor of vertex (a vertex is considered an ancestor of itself). This holds if and only if the interval [d[b]; f[b]] is nested in the interval [d[a]; f[a]].

// if a is a parent of b
int Parent(int a, int b)
{
  return (d[a] <= d[b]) && (f[a] >= f[b]);
}

The LCA function finds the lowest common ancestor of vertices and using binary lifting. If one of the vertices is an ancestor of the other, it is the answer. Otherwise, lift with jumps of length 2^l, 2^{l-1}, \ldots, 1, making a jump only if the new vertex is still not an ancestor of . In the end, the parent is the LCA.

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 cmp function compares vertices by entry time. It is used to sort vertices in the order of the depth-first search.

int cmp(int a, int b)
{
  return d[a] < d[b];
}

The main part of the program. Read the number of vertices and the number of sets .

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

Compute — the smallest number such that 2^l > n. For n \le 2 \cdot 10^5 we get l \le 18, so the second dimension of the array , equal to , is sufficient.

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

Read the edges of the tree and build the adjacency list.

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

Run the depth-first search from vertex . Time is counted starting from .

timer = 1;
dfs(1, 1);

Process the sets. The vertices of the current set are read into the list . For each vertex of the set we set \mathit{sub}[x] = x, and the variable accumulates the sum of the numbers of all vertices of the set modulo .

for (j = 0; j < q; j++)
{
  scanf("%d", &k);
  vt.clear();
  s = 0;
  for (i = 0; i < k; i++)
  {
    scanf("%d", &x);
    vt.push_back(x);
    sub[x] = x;
    s = (s + x) % MOD;
  }

Build the vertices of the compressed tree. Sort the vertices of the set by entry time and add the LCA of each pair of adjacent vertices. Then sort again and remove duplicates with the unique function. We get at most 2k - 1 vertices.

  // build virtual tree: add LCA of neighbours in dfs order
  sort(vt.begin(), vt.end(), cmp);
  for (i = 0; i < k - 1; i++)
    vt.push_back(LCA(vt[i], vt[i + 1]));
  sort(vt.begin(), vt.end(), cmp);
  vt.erase(unique(vt.begin(), vt.end()), vt.end());

Find the parent of each vertex of the compressed tree. We use the STL stack , which stores the path from the root of the compressed tree to the last processed vertex. At the beginning of processing a set, the stack is cleared. Iterate over the vertices of in order of entry time. While the stack is not empty and its top element st.top() is not an ancestor of the current vertex , pop it with the pop function. The remaining top element of the stack is the parent of . If the stack is empty, then is the root of the compressed tree and \mathit{par}[x] = 0. Then push onto the stack with the push function.

  // find parent of each vertex in virtual tree
  while (!st.empty()) st.pop();
  for (i = 0; i < (int)vt.size(); i++)
  {
    x = vt[i];
    while (!st.empty() && !Parent(st.top(), x)) st.pop();
    par[x] = st.empty() ? 0 : st.top();
    st.push(x);
  }

Iterate over the vertices of the compressed tree, except the root , in decreasing order of entry time. By the time vertex is processed, all its descendants have already been processed, and contains the sum of the numbers of the set vertices in the subtree of . The edge (\mathit{par}[x], x) replaces \mathit{dist}[x] - \mathit{dist}[\mathit{par}[x]] edges of the original tree, and each of them contributes \mathit{sub}[x] \cdot (s - \mathit{sub}[x]). After that, add to the value of the parent. The product is computed in parts, taking the remainder after each multiplication, so as not to exceed the range of the long long type.

  // edge (par[x], x) of length dist[x] - dist[par[x]]
  // gives sub[x] * (s - sub[x]) for every its edge
  res = 0;
  for (i = (int)vt.size() - 1; i > 0; i--)
  {
    x = vt[i];
    sub[x] %= MOD;
    res = (res + (dist[x] - dist[par[x]]) * sub[x] % MOD *
          ((s - sub[x] + MOD) % MOD)) % MOD;
    sub[par[x]] += sub[x];
  }

Print the answer for the current set.

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

Reset the values in the vertices of the compressed tree so that they do not affect the next sets. Only the vertices from are reset, so the cleanup time is proportional to the size of the set.

  for (i = 0; i < (int)vt.size(); i++)
    sub[vt[i]] = 0;
}