Counting p-cousins ​​on a directional tree

We are given an oriented tree for work. We define the concepts of p-ancestor and p-cousin as follows

p-ancestor: A node is the 1st ancestor of another if it is its parent. This is the p-ancestor of a node if it is the parent of the (p-1) -th ancestor.

p-cousin: A node is the p-cousin of another if they have the same p-ancestor.

For example, consider the tree below.

Example

4 has three 1-cousins ​​i, e, 3, 4, and 5, since they all have a common 1-ancestor, which is 1

For a particular tree, the problem is as follows. You give a few pairs (node, p) and must calculate (and output) the number of p-cousins ​​of the corresponding nodes.

A slow algorithm would be to scan to the p-ancestor and run BFS for each node.

() ?

+4
3

, .

, n (node, p) 0 n - 1

(node, p) (ancestor , p) :

(node, p), node a ( node a), a a - p. , , :

dfs(int node, int level, int[]path, int[] ancestorForQuery, List<Query>[]data){
    path[level] = node;
    visit all child node;
    for(Query query : data[node])
       if(query.p <= level)
          ancestorForQuery[query.index] = path[level - p];
}

, DFS , (ancestor, p)

, count, i node, i. , node a x p, :

query result = count[x + p] after we visit a -  count[x + p] before we visit a

dfs2(int node, int level, int[] result, int[]count, List<TransformedQuery>[]data){
   count[level] ++;
   for(TransformedQuery query : data[node]){
         result[query.index] -= count[level + query.p];
   }
   visit all child node;
   for(TransformedQuery query : data[node]){
         result[query.index] += count[level + query.p];
   }
}

result.

+1

p , :

, count [v] - p- v. count [v] 0. pparent [v] p- v.

dfs , .. v, . v, .

, node v dfs. count [stack [size - p]] ++, , p- v. pparent [v] = stack [size-p]

dfs , p- v: [pparent [v]]

- O (n + m) dfs O (1)

0

O (p), O (n), , O (log p ) O (log n) .

O (p)

, , DFS, , node , , p- node . , "" , , , ( , ), . , (v, p), :

  • p- u node v. O (p).
  • p- l u - node, , node, p . O (p).
  • p- r u ( ). O (p).
  • x [r] - x [l] + 1, x [i] , , , , node i. .

- x [i], 1 <= <= n. DFS, y [], y [d] , d. , y [d] 0 d; DFS, node v d, y [d], x [v] = y [d].

O (log p) -

, , , node , O (p) = O (n). , 4 , O (p) - .

, , . " ": node v log2 (depth (v)) . , log2 (maxDepth) DFS, i- node v i- (i-1) - (i-1) - ancestor: node DFS. , p, log (p) , . ​​ "-" " " 2 3 O (log p).

0
source

Source: https://habr.com/ru/post/1629112/


All Articles