HDU5536 Chip Factory 01Trie处理xor

2015ICPC长春站J题
给出一个长度为 N N 的数组 s s ,求 max ( s i + s j ) s k \max (s_i+s_j) \bigoplus s_k ,其中 i , j , k i,j,k 互不相同,有多组数据
N 1000 N \leq 1000
辣鸡数据裸 O ( n 3 ) O(n^3) 能过
正解应该是把 N N 个数插入01Trie中,询问时 n 2 n^2 枚举 i , j i,j ,在Trie上删除 s i , s j s_i,s_j 后(因为要求 k i , j k \neq i,j ),再跑一遍贪心求 s i + s j s_i+s_j 能异或得到的最大值,复杂度 O ( n 2 log n ) O(n^2 \log n)
比较基础的01Trie模板题
Code:

#include<bits/stdc++.h>
#define ll long long
#define clr(x,i) memset(x,i,sizeof(x))
using namespace std;
const int N=1005;
const ll mod=1e9+7;
inline int read()
{
    int x=0,f=1; char ch=getchar();
    while(ch<'0'||ch>'9') {if(ch=='-') f=-1; ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,a[N],ch[N*N][2],siz[N*N],tot;
void ins(int x)
{
	int now=0;
	for(int i=30; i>=0; i--){
		bool t=(1<<i)&x;
		if(!ch[now][t]){
			ch[now][t]=++tot;
			ch[tot][0]=ch[tot][1]=0;
			siz[tot]=0;
		}
		now=ch[now][t];
		siz[now]++;
	}
}
void del(int x)
{
	int now=0;
	for(int i=30; i>=0; i--){
		bool t=(1<<i)&x;
		now=ch[now][t];
		siz[now]--;
	}
}
int qry(int x)
{
	int ret=0,now=0;
	for(int i=30; i>=0; i--){
		bool t=(1<<i)&x;
		if(siz[ch[now][t^1]]) ret+=(1<<i),now=ch[now][t^1];
		else now=ch[now][t];
	}
	return ret;
}
void solve()
{
	n=read(); tot=0; ch[0][0]=ch[0][1]=siz[0]=0;
	for(int i=1; i<=n; i++){
		a[i]=read();
		ins(a[i]);
	}
	int ans=0;
	for(int i=1; i<=n; i++){
		for(int j=i+1; j<=n; j++){
			del(a[i]); del(a[j]);
			ans=max(ans, qry(a[i]+a[j]));
			ins(a[i]); ins(a[j]);
		}
	}
	printf("%d\n",ans);
}
int main()
{
	int T=read();
	while(T--) solve();
}

/*
void bf()
{
	n=read();
	int ans=0;
	for(int i=1; i<=n; i++) a[i]=read();
	for(int i=1; i<=n; i++){
		for(int j=i+1; j<=n; j++){
			for(int k=1; k<=n; k++){
				if(k==i || k==j) continue;
				ans=max(ans, (a[i]+a[j])^a[k]);
			}
		}
	}
	printf("%d\n",ans);
}
*/

//一年多没有写过博客了啊,这一年将多少梦想化为了现实,又带着多少遗憾继续前往远方了呢?

发布了39 篇原创文章 · 获赞 4 · 访问量 5803

猜你喜欢

转载自blog.csdn.net/Wolf_Reiser/article/details/103150800
今日推荐