codeforces 888G Xor-MST(01字典树)

本文介绍了一种使用01Trie树解决寻找两个集合中元素的最小异或值问题的方法。通过构建特定的二叉树结构,并采用高效算法遍历树来寻找最小异或值对,避免了暴力匹配的时间复杂度过高的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

这题主要操作就是建立一棵01Trie树(其实就是一颗普通的二叉树嘛),由于最大值小于2^30,所以最大树高到30就好了,在树的分叉点上,左子树和右子树分别是两个集合(集合的size是叶节点的数量),根分别为A和B,深度(假设叶子节点的深度为1)为h,合并(连接)这两个集合的时候,需要从这两个集合选出两个异或值最小的数。

那么重点就是如何去选这两个数。一开始想的是暴力对比,将左右子树的数字每对都计算一遍异或,时间肯定爆炸了。

方法是选出size较小的那个集合(假设是左子树的集合),将集合中的每一个数按位从节点B开始往下走,从第h位开始一位一位地往下比对,如果对比到当前节点没有左节点的话,就走右节点,没有右节点就往左走,如果左右都有就看当前数字的对比位是0还是1,如果是1就往1的的那个节点走。最后走到叶节点就是当前数在该子树上异或能取得的最小值。

时间复杂度是树高(30)乘以节点数量2e5再乘以logn,大约一亿左右,两秒能过


#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<vector>
using namespace std;
const int maxn = 2e5 + 5;
int n, a;
struct Trie
{
	Trie(int H) :h(H), l(NULL), r(NULL) {}
	vector<int> vec;
	int h;
	Trie *l, *r; //l->1, r->0
} T(31);
int min(int a, int b)
{
	return a < b ? a : b;
}
long long solve(Trie *t)
{
	if (t == NULL)return 0;
	long long ans = 0;
	Trie *tl = t->l, *tr = t->r, *temp;
	ans += (solve(tl) + solve(tr));
	
	if (tl && tr)
	{
		int m = 0x5f3f3f3f;
		if (tl->vec.size() < tr->vec.size())
		{
			for (vector<int>::iterator i = tl->vec.begin(); i != tl->vec.end(); i++)
			{
				int x = *i;
				temp = tr;
				for (int j = t->h - 2; ~j; j--)
				{
					if (!temp->l)temp = temp->r;
					else if (!temp->r) temp = temp->l;
					else
					{
						if (x >> j & 1)
							temp = temp->l;
						else
							temp = temp->r;
					}
				}
				m = min(m, x ^ temp->vec[0]);
			}
		}
		else
		{
			for (vector<int>::iterator i = tr->vec.begin(); i != tr->vec.end(); i++)
			{
				int x = *i;
				temp = tl;
				for (int j = t->h - 2; ~j; j--)
				{
					if (!temp->l)temp = temp->r;
					else if (!temp->r) temp = temp->l;
					else
					{
						if (x >> j & 1)
							temp = temp->l;
						else
							temp = temp->r;
					}
				}
				m = min(m, x ^ temp->vec[0]);
			}
		}
		ans += m;
	}
	return ans;
}
int main()
{
	cin >> n;
	Trie *temp;
	while (n--)
	{
		temp = &T;
		cin >> a;
		for (int j = 30; ~j; j--)
		{
			if ((a >> j) & 1)
			{
				if (!temp->l)temp->l = new Trie(j);
				temp = temp->l;
			}
			else
			{
				if (!temp->r)temp->r = new Trie(j);
				temp = temp->r;
			}
			temp->vec.push_back(a);
		}	
	}
	cout << solve(&T) << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值