CodeChef--July Lunchtime 2014_And Operation

                                               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 < vN) 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 < vN.

 

Constraints

50 points:

  • 2N5000
  • 0Ai109

50 points:

  • 2N3 × 105
  • 0Ai109

 

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值