Official

F - Logical Operations on Tree Editorial by evima


Let us first consider the decision problem where the vertices and edges are already labeled. We say a tree is good when we can make the last remaining vertex labeled 1.

The case \(N=1\) is obvious. Let us handle the other cases.

If a leaf is labeled 1, and the edge incident to that leaf is labeled OR, we can do the operation on this edge last to make the final vertex labeled 1, so it is a good tree.

Below, we assume that the given tree does not have such a part. Then, there are three important facts, as follows:

  • If a leaf is labeled 0 and the edge incident to that leaf is labeled AND, whenever we do the operation on this edge, the label of the vertex adjacent to the leaf will become \(0\). If the tree after doing this operation is good, the original tree is also good.

  • If a leaf is labeled 0 and the edge incident to that leaf is labeled OR, whenever we do the operation on this edge, the label of the vertex adjacent to the leaf will not change. If the tree after doing this operation is good, the original tree is also good.

  • If a leaf is labeled 1 and the edge incident to that leaf is labeled AND, whenever we do the operation on this edge, the label of the vertex adjacent to the leaf will not change. If the tree after doing this operation is good, the original tree is also good.

From these facts, it can be seen that we can keep doing operations on leaves greedily to solve the decision problem. Below, let us consider the counting problem.

Let the tree rooted at Vertex \(1\). Consider doing operations on the subtree rooted at Vertex \(i\). If we get a 1-OR leaf during the operations, the tree is good, no matter how the remaining part of the tree is labeled. If we do not get such a leaf during the operation, we can leave the descendants of Vertex \(i\) deleted. That is, doing operations on the subtree leads to one of the following three states:

  • The tree is confirmed to be good.
  • 0 is written on Vertex \(i\).
  • 1 is written on Vertex \(i\).

Maintaining such states, we can do DP to solve the problem in \(O(N)\) time, which is fast enough.

posted:
last update: