6358: 庭师的利刃
时间限制: 1 Sec 内存限制: 128 MB
提交: 729 解决: 145
[提交] [状态] [讨论版] [命题人:admin]
题目描述
作为白玉楼的庭师,妖梦虽然不会n刀流,但是却领悟了生命二刀流。然而我也是个剑的收藏者,家里屯着n把剑,每一把剑都有一个灵魂值a[i],由于一些剑之间可能有共鸣,所以我需要两把契合度最高的剑。据妖梦所说,两把编号为i,j剑的契合度为a[i] and a[j]。如何深得剑的灵魂呢?(即求最大值)
输入
第一行一个整数n,代表藏剑数。
第二行n个整数,第i个整数表示a[i]。
输出
输出包含一个正整数,最好的两把剑的契合度。
样例输入
5 12 5 6 3 1
样例输出
4
提示
对于40%的数据 n ≤ 1,000
对于100%的数据 n ≤ 1,000,000,0 ≤ a[i] < 2^31
思路:高位1越多与运算的结果越大,首先对所有数从大到小排序,如果有两个或更多数在第i位都为1,那么答案一定是从这些数里得到的,每次用vector记录这些数,因为已经排过序了,所以记录的数肯定是高位为1的排在前面,然后对vector里的数重复筛选,最后得出结果。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
#define M(a,b) memset(a,b,sizeof(a))
#define pb push_back
typedef long long LL;
const int maxn = 100005+5;
const LL mod = 1000000007;
int a[(maxn<<2)+(maxn<<3)];
bool cmp(const int &a,const int &b) {
return a>b;
}
int main() {
int n;
scanf("%d",&n);
for (int i=1;i<=n;++i) {
scanf("%d",a+i);
}
sort(a+1,a+1+n,cmp);
vector<int>ans,tmp;
for (int i=30;~i;--i) {
int cnt=0;
if (!ans.size() || ans.size()<=1) {
ans.clear();
for (int j=1;j<=n;++j) {
if (a[j]&(1<<i)) {
ans.pb(a[j]);
}
}
}
else {
tmp.clear();
for (int j=0;j<ans.size();++j) {
if (ans[j]&(1<<i)) {
tmp.pb(ans[j]);
}
}
if (tmp.size()>=2) {
ans=tmp;
}
}
}
if (ans.size()<2) {
puts("0");
}
else {
printf("%d\n",ans[0]&ans[1]);
}
return 0;
}