原文链接:https://blog.csdn.net/qq_41021816/java/article/details/82934486
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:
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?
输入
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≤s i≤109
There are at most 10 testcases with n > 100
输出
For each test case, please output an integer indicating the checksum number in a line.
样例输入
2
3
1 2 3
3
100 200 300
样例输出
6
400
题目大意:
给 N 个数,在这 N 个数里找到三个不同的数字 i, j,k 使得(i+j)⊕ k 最大,输出这个最大值。
解题思路:
把每个数字看成一个0101字符串插入倒Trie树中去,枚举i和j,然后把si和sj从Trie树中删去。
然后在Trie树中贪心找到能与si+sj异或得到的最大值。
具体匹配的过程中是这样的,首先看树中最高位能否异或得到1。
能的话就往能的那个方向走,否则往另外一个方向走。
另外删除操作是这样实现的,我们每个节点记录一个num值。
插入时对所有经过节点的num值加1,删除就将对应节点的num值减1。
在树上匹配的时候就只走那些num值为正的节点。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int a[2005],ch[35*1005][2],val[35*1005];
int tol;
void insert(ll x,ll p)
{
int u=0;
for(int i=31;i>=0;i--)
{
int v=(x>>i)&1;
if(!ch[u][v])
ch[u][v]=tol++;
u=ch[u][v];
val[u]+=p;
}
}
ll query(ll x)
{
int u=0;
ll ans=0;
for(int i=31;i>=0;i--)
{
int v=(x>>i)&1;
if(val[ch[u][v^1]])
u=ch[u][v^1],ans=ans<<1|1;
else
u=ch[u][v],ans=ans<<1;
}
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
tol=1;
int n;
scanf("%d",&n);
for(int i=0;i<=n*32;i++) //建立整个TRIE
ch[i][0]=ch[i][1]=val[i]=0;
for(int i=1;i<=n;i++) //将每个数字加入到TRIE中
{
scanf("%d",&a[i]);
insert(a[i],1);
}
ll maxx=0;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
insert(a[i],-1); //删除A[i],a[j]
insert(a[j],-1);
maxx=max(maxx,query(a[i]+a[j]));
insert(a[j],1);
insert(a[i],1);
}
}
printf("%lld
",maxx);
}
return 0;
}
然而。。。。
#include <cstdio>
#include <algorithm>
using namespace std;
int a[1005];
int main()
{
int T;
scanf("%d", &T);
while(T --)
{
int n, ma = 0;
scanf("%d" ,&n);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
for(int k = j + 1; k < n; k++)
{
ma = max(ma, (a[i] + a[j]) ^ a[k]);
ma = max(ma, (a[i] + a[k]) ^ a[j]);
ma = max(ma, (a[j] + a[k]) ^ a[i]);
}
printf("%d
", ma);
}
}