Codeforces 702 B. Powers of Two(二分)

传送门

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
input
4
7 3 2 1
output
2
input
3
1 1 1
output
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(n<=10^5) 个数a[i] (1<=i<=n),然后,从中选两个数 a[i] , a[j] (i < j) 满足 a[i]+a[j] = 2^x
解题思路:
因为 a[i] + a[j] 不会超过 2^31,所以 我们暴力枚举 1-31就行,然后暴力二分找 2^x - a[i] == a[j]的数,先 lower_bound()一下,然后在upper_bound一下就能找到相等的了,ans += 下标差值就行了。

My Code:

/**
2016 - 08 - 02 上午

Author: ITAK
Motto:

今日的我要超越昨日的我,明日的我要胜过今日的我,
以创作出更好的代码为目标,不断地超越自己。
**/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int MAXN = 1e6+5;
const int MOD = 1e9+7;
const double eps = 1e-7;
LL a[MAXN];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; i++)
            scanf("%lld",&a[i]);
        sort(a, a+n);
        LL cnt = 0;
        for(int i=1; i<=32; i++)
        {
            LL ans = (1LL<<i);
            if(ans > 2*a[n-1])
                break;
            for(int j=0; j<n-1; j++)
            {
                int tp1 = lower_bound(a+j+1, a+n, ans-a[j])-a;
                int tp2 = upper_bound(a+j+1, a+n, ans-a[j])-a;
                if(tp1 == n)
                    continue;
                int tmp = tp2 - tp1;
                cnt += tmp;
            }
        }
        cout<<cnt<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值