First we set DP [i] [x] [y] [k] represents the current to the i-th layer which x buds (node also may continue to grow), the next layer buds y, has been selected the k leaves (so that the k-th node becomes a leaf node)
Then transferred directly to enumerate what this layer with a p y become a leaf node can then count the cost of the end
You can use the prefix and optimize it. Provided SUM [i] represents the number of times of occurrence and before i
dp[i][x][y][k]=min(dp[i+1][x+y-p][x-p][k+p]+sum[n]-sum[k+p])
Here is pushed backwards
Consider optimization
We found that the first dimension seems useless
Better to save it
We set dp [x] [y] [k] represents the bottom layer buds x, y buds next level, we have selected the k leaves.
When the transfer of direct enumeration y the end of this layer of p, note this is not the cost of each element on the end of the record, we did not floor when down in, we count on the contribution of this layer will produce.
dp[x][y][k]=min(dp[y+x-p][y-p][k+p]+sum[n]-sum[k+p])
Complexity o (n ^ 4)
This complexity does not work
Obviously the state has not optimized, consider optimizing transfer
Now the transfer is o (n), because of the reasons enumerated p
Let us choose a point every time, do not want to choose the time and then went to the next level
dp[x][y][k]=min(dp[x][y-1][k+1],dp[x+y][y][k]+sum[n]-sum[k])
Complexity of O (n ^ 3)