感谢波兰的红名大牛Errichto的讲解。
这道题中涉及到了两个操作,一个是加倍,另外一个除2并向下取整。这如果放在一个二叉树上的操作无非就是向上到达其父节点,向下(只能走左孩子)到达其子节点。我直接贴大牛的原话吧
Let's say input is n = 3 and array 2,5,6. Let's think about a binary tree with 7 (in my code there are always 2^17-1) nodes where node number x has children 2*x and 2*x+1. Root has number 1. Now let's think about it as a graph. There is one "thing" in node number 2, one in node number 5, one in node number 6. What is a node minimizing sum of distances to these "things"?
Note: we can only go up (to parent) or to the left son. Going up means dividing by 2 and going to left son means multiplying by 2.
现在的关键是找到这个节点,使得所有的元素到达它所需要的花费最小。
这里我们需要用上两个数组,一个数组res需要记录的是点x的子树到达其顶点x所需要的花费;一个数组count记录的是点x有多少个数能够达到。就拿上面的例子来说吧
count[5]=count[6]=1是因为这两个数本身就已经存在了,而count[2]=2的原因是count[5]是做为该节点的右孩子,这说明是可以到达的,后面count[1]=3,count[3]=1原因也是如此。
而另外一个数组res的值得求法应该是
res[x]=res[2*x]+res[2*x+1]+count[2*x]+count[2*x+1]
原因和其定义有关因为res[x]代表其子树到达其顶点的花费,而这些花费不能代表该顶点到达其父节点的花费,简而言之就是要加上自己的花费和它的子树到达它的花费。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<fstream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL;
#define mmax 128*1024
LL res[mmax];
LL cont[mmax];
LL ans = (LL)mmax*mmax;
void rec(int i, int RES, int COU)
{
ans = min(ans, RES + res[i]);
if (i > mmax / 2) return;
int itsValue = cont[i] - cont[2 * i] - cont[2 * i + 1];
rec(2 * i, RES + res[2 * i + 1] + 2 * cont[2 * i + 1] + itsValue + COU, COU + cont[2 * i + 1] + itsValue);
if (res[2 * i] + itsValue + COU == 0)//当左支已经无法达到,这时跳转右支,算右支的子树
rec(2 * i + 1, RES + res[2 * i] + 2 * cont[2 * i] + itsValue + COU, COU + cont[2 * i] + itsValue);
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int a;
scanf("%d", &a);
cont[a]++;
}
for (int i = mmax / 2; i>0; i--)
{
res[i] = res[i * 2] + res[i * 2 + 1] + cont[2 * i] + cont[2 * i + 1];
cont[i] += cont[2 * i] + cont[2 * i + 1];
}
rec(1, 0, 0);
cout << ans << endl;
return 0;
}