To Dr. John Fawcett and Dr. Luana Bulat - Virtual Tree

0x01. Hello!

Hello, Dr. John Fawcett and Dr. Luana Bulat, thank you for viewing this article. This work is about Virtual Tree, an algorithm designed to improve the time complexity of doing dynamic programming on trees.

0x02. An Example of Virtual Tree

Dr. John Fawcett said that we can set up lots of questions based on water flowing through a pipe.

Imagine that: there are n houses and there are also n1 water pipes connecting each of them, a group of evil aliens occupied the first house for no reason (they might like the number 1), now these aliens are planning to attack k houses through water pipe (they are liquid creatures!). We are now given that the details of these n1 water pipes (where it starts from, where it ends and the cost of cutting it), we are required to destroy certain pipes so that these aliens cannot attack any of their targets. What is the lowest cost of doing this.

For example, there are ten houses and they are connected like this:

3
1
2
4
3
6
2
10
2
1: Aliens are in this house
2
4
3
5: Target
10
6
7: Target
8
9: Target

To prevent these aliens reaching any targets, the lowest cost is 5: we only need to cut the 1 -> 2 pipe and 1 -> 3.

It is a very basic dynamic programming on trees question and the state transition equation is not hard to think of.

Let:

  1. i represent the current node we are working on, j represent a certain son of i

  2. v(i>j) represent the cost of cutting the pipe which connects i and j.

  3. f(i) represent the minimum cost of preventing aliens reaching its targets in the subtree of i.

    According to the clarification to variables, we have got the state transition equation: f(i)=min( f(j),v(i>j) ).

0x03. Complicated Situation & Virtual Tree

Clearly, if we do not apply any improvements to that implement, the time complexity is O(n) which is fine when n is small. However, the efficiency of this implement is low as it considers some irrelevant nodes. To improve the efficiency of it, we need to predict which node is needed and which is not, that is the job for virtual tree to handle.

A virtual tree is a simplified edition of original tree for the reason that it only saves necessary nodes.

An example for virtual tree

The left hand side tree is the original tree and the right hand side is a virtual tree

0x04. Build And Apply Virtual Tree

In this question, because we only need to consider the targets so we can build a virtual tree includes and only includes the targets and their lowest common ancestors.

The process is below (LCA(a,b) means the lowest common ancestor of nodes a and b):

Now array A is the virtual tree, we can do the dynamic programming on A (because this is graph is a tree, so I prefer using edge list).

Here is the enhanced complete code (written in C++) for Codeforces Round #339 Div. 1 (in this question the value of the each edge is 1, but in my code, ith edge has a value mi):