CodeForces 702B Powers of Two(二分)

B. Powers of Two

time limit per test

3 seconds

memory limit per test

256 megabytes

input

standard input

output

standard 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

input

Copy

4
7 3 2 1

output

Copy

2

input

Copy

3
1 1 1

output

Copy

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.

题目大意:给你n个数字,问你这些数字中能找出几对数字使得是2的幂次方

思路:题意很简单,然后思路也很好想,,暴力肯定不行,我想到用二分做,先把int范围以内2的幂都求出来,大概31位就可以了,然后2的幂减去该数组,再在原本的数组中二分查找。。。但是本题用原来的二分可能不是很好做,例如第二个样例,1 1 1,当你查找第一个的时候可能找到第一个1就结束了,但是第二个1根本没查找到,所以原来的二分可能比较难做,这里我们用到,C++的STL函数中的upper_bound和lower_bound,第一个是二分找到所有大于要查找的数,第二个二分是找到所有大于等于的数,二者再减一下就可以了。

代码:

/*

*/
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<cmath>
#include<string>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll unsigned long long
#define inf 0x3f3f3f
#define esp 1e-8
#define bug {printf("mmp\n");}
#define mm(a,b) memset(a,b,sizeof(a))
#define T() int test,q=1;scanf("%d",&test); while(test--)
const int maxn=2e5+100;
const double pi=acos(-1.0);
const int N=1100;
const int mod=1e9+7;

int a[maxn];
int b[maxn];
void ff()
{
    a[1]=1;
    for(int i=2; i<32; i++)
        a[i]=a[i-1]*2;
}

int main()
{
    ff();
    int n;
    ll cnt=0;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        cin>>b[i];
    sort(b,b+n);
    for(int i=0; i<n; i++)
    {
        for(int j=1; j<=31; j++)
        {
            int ans=a[j]-b[i];
            if(ans<=0)
                continue;
            else
            {
                cnt+=upper_bound(b+i+1,b+n,ans)-lower_bound(b+i+1,b+n,ans);
            }

        }
    }
    printf("%lld\n",cnt);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lee371042/article/details/88956144
今日推荐