Contest Duration: - (local time) (210 minutes) Back to Home
Official

F - NAND Tree Editorial by rng58_admin

Suppose that we first perform an operation on edge $$e_1$$, and the next operation on edge $$e_2$$. In most cases, even if we swap the order of the first two edges ($$e_2 \rightarrow e_1$$ instead of $$e_1 \rightarrow e_2$$), we get the same results, and they cancel out in modulo $$2$$. The only exception happens when $$e_1$$ and $$e_2$$ shares a vertex in common, so we can assume that the first two operations are performed on adjacent edges.

There are two ways to perform two operations on the part x --- y --- z. In one way we get a NAND(NAND(y, x), z), and in the other way we get a NAND(NAND(y, z), x). In case $$x = z$$, these two are the same and cancel out in modulo $$2$$, and in case $$x \neq z$$, it turns out that we get two distinct results in two ways.

Here is the key observation. The answer to the problem doesn’t change even if we modify the rule in the following way: choose a vertex, and it “eats” two edges as the following diagram shows.

  \       |      /                       \ | /
--- x --- y --- z ---        =>        --- x ---
/       |      \                       / | \


Note that under this rule it is also possible to get $$z$$ after the operation by performing the operation from a different direction. Thus, again, those two ways cancel out iff $$x = z$$.

Now, let’s solve this modified problem. For simplicity, assume that the initial tree has even number of edges. Let’s call a vertex good if there are odd number of ways to perform operations to make the vertex the “winner” after we finish operations. The answer is the number of good vertices that are initially labelled with $$1$$.

How to check if a vertex is good? Let’s root the tree and check if the root is good. We can assume that we never perform operations that doesn’t involve the root (otherwise two possible directions of the operation cancel out each other), and we can count the number of ways to perform operations that always involve the root, by a simple tree DP. It is also possible to show that the parity of this number is equal to the number of possible topological sorts of the rooted tree (this observation simplifies the implementation).

What if the given tree has odd number of edges? Just try all possibilities for the first edge and it reduces to even-edge cases.

posted:
last update: