Official

D - Two Balanced Subtrees Editorial by evima


We recursively construct an assignment where vertex \(1\) has \(1\) written.

For \(N=1\), the answer is \((1)\).

Let \(P\) be the answer for \(N-1\). Set \(L=P\) and \(R=P\), and construct as follows.

  1. For each \(i=1,2,\ldots,2^{N-1}-1\), add \(1\) to \(L_i\) and add \(2^{N-1}-1\) to \(R_i\).
  2. Set \(R_1=2^N-1\).
  3. For each \(i=2^{N-2},\ldots,2^{N-1}-1\), swap \(L_i\) and \(R_i\).
  4. Write \(1\) on vertex \(1\), write \(L\) on the subtree of vertex \(2\), and write \(R\) on the subtree of vertex \(3\).

This assignment satisfies the condition. It can be verified by straightforward computation that it is a permutation and that the absolute difference between the sums of the two subtrees is \(1\).

posted:
last update: