Codeforces Round #312 div 2 C的二叉树实现

        感谢波兰的红名大牛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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值