Statement

You are given a binary tree with weighted nodes. Operating on edge (𝑢,𝑣) swaps 𝑤𝑢 and 𝑤𝑣 for cost 𝑤𝑢+𝑤𝑣. Find the minimum total cost to operate on every edge exactly once, in any order. (https://qoj.ac/problem/4054)

Solution

First, observe that the left and right subtrees of a node are almost independent. Any configuration in which edges from the two subtrees are interleaved can be shown to be equivalent to one of two cases:

  1. All edges in the left subtree are operated before any edge in the right subtree.
  2. All edges in the right subtree are operated before any edge in the left subtree.

Assume WLOG that we operate the left subtree first, and let our root node be 𝑢. Then, for the left subtree, we only care about two things:

  1. which node 𝑥 node 𝑢 ends up in
  2. which node 𝑣 from the left subtree ends up in position 𝑢

Then, we can plug 𝑣 into the right subtree and minimize. This yields a pretty simple 𝒪(𝑛3) solution, where dp[u][x][y] represents the minimum cost to delete all edges in the subtree of 𝑢, while moving fa(𝑢) to 𝑥 and moving 𝑦 to fa(𝑢).

An important observation from here is to notice that 𝑥 and 𝑦 must satisfy lca(𝑥,𝑦)=𝑢, otherwise it’s surely impossible. This immediately reduces the number of states to only 𝒪(𝑛2). To optimize our runtime to also be 𝒪(𝑛2), note that we can optimize dimensions incrementally, rather than all at once.

For instance, consider the case where our operation order is (fa(𝑢),𝑢), then left subtree, then right subtree.

In the last step, since we care about neither where the green node ultimately settles nor what the red node is, we can precompute into_r[x] as the minimum cost to move 𝑥 (the green node) anywhere into the right subtree and get any node out. We can show that in total over all 𝑢, this step takes only 𝑂(𝑛2) time. Similar pre-computation can be applied in other cases, leading to a overall runtime of 𝒪(𝑛2).

My submission: https://qoj.ac/submission/1878265