Codeforces 702 B. Powers of Two(二分)

来源:互联网 发布:sql insert 单引号 编辑:程序博客网 时间:2024/06/05 22:34

传送门

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: ITAKMotto:今日的我要超越昨日的我,明日的我要胜过今日的我,以创作出更好的代码为目标,不断地超越自己。**/#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;}
0 0
原创粉丝点击