HDU - 5536 Chip Factory【0-1字典樹】

John is a manager of a CPU chip factory, the factory produces lots of chips everyday. To manage large amounts of products, every processor has a serial number. More specifically, the factory produces n chips today, the i-th chip produced this day has a serial number si.
At the end of the day, he packages all the chips produced this day, and send it to wholesalers. More specially, he writes a checksum number on the package, this checksum is defined as below:
maxi,j,k(si+sj)⊕sk
which i,j,k are three different integers between 1 and n. And ⊕ is symbol of bitwise XOR.
Can you help John calculate the checksum number of today?

Input
The first line of input contains an integer T indicating the total number of test cases.
The first line of each test case is an integer n, indicating the number of chips produced today. The next line has n integers s1,s2,…,sn, separated with single space, indicating serial number of each chip.
1≤T≤1000
3≤n≤1000
0≤si≤109
There are at most 10 testcases with n>100

Output
For each test case, please output an integer indicating the checksum number in a line.

Sample Input
2
3
1 2 3
3
100 200 300

Sample Output
6
400

題意:在一個數組中找出 (s[i] + s[j]) ^ s[k] 的最大值,其中 i、j、k 各不相同。
思路:看數據範圍可以想到暴力+字典樹,有一個要注意的就是,s[i]+s[j]不能與自己異或,所以我們要用一個更新操作,將s[i]和s[j]路徑上的值都減一

#include<bits/stdc++.h>
using namespace std;
#define maxn 100010
typedef long long ll;
struct Tire{
	ll siz,ch[32*maxn][2],val[32*maxn],vis[32*maxn];
	void tire_clear(){siz=1,memset(ch[0],0,sizeof(ch[0]));}
	void tire_insert(ll x){
		int u=0; 
		for(int i=32;i>=0;i--){
			int c=(x>>i)&1;
			if(!ch[u][c]){//節點不存在 
				memset(ch[siz],0,sizeof(ch[siz]));
				val[siz]=0; vis[siz]=0;
				ch[u][c]=siz++;//新建節點 
			}
			u=ch[u][c];//往下走 
			vis[u]++;
		}
		val[u]=x;//字符串的最後一個字符的附加信息爲v
	}
	void tire_update(ll x,int d){
		int u=0;
		for(int i=32;i>=0;i--){
			int c=(x>>i)&1;
			u=ch[u][c];
			vis[u]+=d;
		}
	}
	ll tire_find(ll x){
		int u=0;
		for(int i=32;i>=0;i--){
			int c=(x>>i)&1;
			if(ch[u][c^1]&&vis[ch[u][c^1]]) u=ch[u][c^1];
			else u=ch[u][c];
		}
		return val[u]^x;
	} 
}tire;
ll a[maxn];
int main(){
	int t; scanf("%d",&t);
	while(t--){
		tire.tire_clear();
		int n; scanf("%d",&n);
		for(int i=1;i<=n;i++){
			scanf("%lld",&a[i]);
			tire.tire_insert(a[i]);
		}
		ll mx=0;
		for(int i=1;i<=n;i++){
			for(int j=i+1;j<=n;j++){
				tire.tire_update(a[i],-1);
				tire.tire_update(a[j],-1);
				ll x=a[i]+a[j];
				mx=max(mx,tire.tire_find(x));
				tire.tire_update(a[i],1);
				tire.tire_update(a[j],1);
			}
		} 
		printf("%lld\n",mx);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章