CF1285D. Dr. Evil Underscores(字典树+贪心+递归)

题目链接:https://vjudge.net/contest/363072#problem/F
http://codeforces.com/problemset/problem/1285/D
在这里插入图片描述在这里插入图片描述题意:找到一个X使得X与每一个值的异或值中的最大值最小
解题思路:
利用字典树,将每一个ai化成01串,放在字典树中。如果一个位数中,既有0又有1出现,那么这个地方的异或一定会有2^step出现。找到最大的一个异或位数之后,就直接两边递归去找最小就行了。主要还是递归有点难理解,可以根据例子自己去试。
另外tri数组要开的足够大,不然就RE了

#include<iostream>
#include<cstdio>
using namespace std;
int n;
int tri[2100000][2];
int a[110000];
int cnt;
void insert(int x)
{
	int pos=0;
	for(int i=29;i>=0;i--)
	{
		int to=(x>>i)&1;
		if(!tri[pos][to])
			tri[pos][to]=++cnt;
		pos=tri[pos][to];
	}
}
int dfs(int step,int pos)
{
	if(step==-1)
		return 0;
	if(!tri[pos][0])
		return dfs(step-1,tri[pos][1]);
	else if(!tri[pos][1])
		return dfs(step-1,tri[pos][0]);
	else
		return min(dfs(step-1,tri[pos][1]),dfs(step-1,tri[pos][0]))+(1<<step);
}

int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
		insert(a[i]);
	}
	cout<<dfs(29,0)<<endl;
	return 0;
}
原创文章 65 获赞 3 访问量 2101

猜你喜欢

转载自blog.csdn.net/littlegoldgold/article/details/105019877