枚举+二分查找(May 17 training problem D)

B. Powers of Two
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given n integers a1, a2, …, an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).

Input
The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers.

The second line contains n positive integers a1, a2, …, an (1 ≤ ai ≤ 109).

Output
Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.

Examples
inputCopy
4
7 3 2 1
outputCopy
2
inputCopy
3
1 1 1
outputCopy
3
Note
In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).
In the second example all pairs of indexes (i, j) (where i < j) include in answer.

看到这题,一开始我想的是枚举i和j,但这是o(nn)的做法会超时,所以要转换枚举对象,枚举对象变成i和x,1<=X<=31,这样就是311e5的时间复杂度,利用这两个把要求的a[j]算出。要理解清楚题目,题目i<j,i从1-n,相当于不重不漏的把每一钟可能的情况进行了遍历,清楚了这一点,就可以对a数组进行sort,对每个i,x算出对应的a[j],从i往后不重不漏的找a【j】出现的次数,需用二分查找(o(logn)的时间复杂度)的算法,
二分查找
upper_bound(a+i+1,a+n+1,temp)-lower_bound(a+i+1,a+n+1,temp);
upper_bound 是从【a+i+1,a+n】找大于temp的第一个数的地址,lower_bound是从【a+i+1,a+n】找等于temp的第一个数的地址,若没找到,则返回第一个大于temp的地址,就和upper_bound相同。
例如 : temp=5,1 2 3 5 5 6,upper_bound(a+0+1,a+n+1,temp)-lower_bound(a+0+1,a+n+1,temp)=2,得到5出现的次数为2
注意一点upper_bound和lower_bound都是左闭右开,与sort类似。

附上ac代码:
#include<bits/stdc++.h>
typedef long long ll;
typedef double db;
#define dep(i,a,b) for(int i=(a);i>=(b);i–)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define mes§ memset(p,0,sizeof§)
using namespace std;
int main()
{
int n,a[100005],b[31];b[0]=1;ll ans=0;
rep(i,1,31)
b[i]=b[i-1]*2;
cin>>n;
rep(i,1,n)
scanf("%d",&a[i]);
sort(a+1,a+1+n);
rep(i,1,n)
rep(j,1,31){
int temp=b[j]-a[i];
if(temp>0){
ans+=upper_bound(a+i+1,a+n+1,temp)-lower_bound(a+i+1,a+n+1,temp);
}
}
cout<<ans<<endl;
return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值