And Operation
Given an array of n non-negative integers: A1, A2, …, AN. Your mission is finding a pair of integers Au, Av (1 ≤ u < v ≤ N) such that (Au and Av) is as large as possible.
And is a bit-wise operation which is corresponding to & in C++ and Java.
Input
The first line of the input contains a single integer N. The ith line in the next N lines contains the Ai.
Output
Contains a single integer which is the largest value of Au and Av where 1 ≤ u < v ≤ N.
Constraints
50 points:
- 2 ≤ N ≤ 5000
- 0 ≤ Ai ≤ 109
50 points:
- 2 ≤ N ≤ 3 × 105
- 0 ≤ Ai ≤ 109
Example
Input: 4 2 4 8 10 Output: 8
Explanation
- 2 and 4 = 0
- 2 and 8 = 0
- 2 and 10 = 2
- 4 and 8 = 0
- 4 and 10 = 0
- 8 and 10 = 8
题目大意是给你n个整数,从中找出两个整数u,v,使得u&v得到最大值(&是c++中的和运算,等于pascal中的and)。
一开始我想到了暴力,枚举每一对然后比较,N最大是3*10^5,枚举是(1+3*10^5-1)*(3*10^5)/2,估计算一下应该是超过10^9,就TLE了。
暴力代码:
#include<iostream>
using namespace std;
const long maxx=3*100000;
long a[maxx];
long ans;
long n;
int main()
{
cin>>n;
for(int j=1; j<=n; j++)
cin>>a[j];
for (int i=1; i<=n; i++)
for (int j=i+1; j<=n; j++)
{
long c;
c=a[i]&a[j];
ans=max(ans,c);
}
cout<<ans<<endl;
return 0;
}
然后我觉得应该有什么规律,应为我找不到别的算法来优化。这条题的时间复杂度应该可以从O(n^2)→O(n),然后我用程序枚举了1....2...100&8的值发现除了0,就是8了。
上面的例子是8&10为最大,比较一下看看。
8的二进制是1000
10的二进制是1011
8&10 得到 1000
发现了没,如果u,v的二进制第一位相同那么他们得到的&运算会尽可能的大,u,v的二进制第一位要相同,那么他们之前的差距要尽可能的小。
所以我们每一次只需要比较排序后,每两两之间的&运算就行了。
O(n)代码:
#include<iostream>
#include<algorithm>
using namespace std;
long n;
long a[300005];
long maxx=0;
int main()
{
cin>>n;
for (int i=1; i<=n; i++)
cin>>a[i];
sort(a+1, a+n+1);
for (int i=1; i<=n-1; i++)
{
long b=a[i]&a[i+1];
maxx=max(maxx,b);
}
cout<<maxx<<endl;
return 0;
}