899. Orderly Queue
非常好的一道題!
觀察,如果 $k = 1$ 的話,你可以得到什麼呢?如果 $k = 2$ 的話,你可以得到什麼呢?
$k = 1 \rightarrow$ 你可以做 logical left shift
$k = 2 \rightarrow$ 你可以對任意兩點做 swap !
非常好的一道題!
觀察,如果 $k = 1$ 的話,你可以得到什麼呢?如果 $k = 2$ 的話,你可以得到什麼呢?
$k = 1 \rightarrow$ 你可以做 logical left shift
$k = 2 \rightarrow$ 你可以對任意兩點做 swap !
It’s basically cutting stick DP. For the given range, try using every possible value as the root, and then D&C
Permutation, without duplicate!
我們先看看如果只要求取以$0$為root的tree下的distance,對於每個 node 都記錄對於他來說的 subtree nodes (including self) 和 subtree total path sum。可以發現,$0$ 的答案就是所有子樹的 = node count + 所有子樹的 total path sum
對於所有其他非 0 的 node,我們如果把它當 root 看,誒,不就是從 0 開始 dfs 到他時,把他的parent那邊當做 subtree 看了嗎!