codeforces-702B-Powers of Two

来源:互联网 发布:celtx剧本写作软件 编辑:程序博客网 时间:2024/06/05 16:10

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.

这道题在做教育场的时候并没有想到怎么做,一直T14,后来做完之后才听别人说的,大概就是数据范围内2的幂,只有30个,然后二分去找它减一减就好了

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef long long ll;const int maxn = 1e5 + 10;int n;ll a[maxn];ll p[40];int main(){    while(scanf("%d",&n)!=EOF)    {    for(int i = p[0] = 1; i <= 32; i++) p[i] = p[i-1] *2;    ll ans = 0;    for(int i = 0; i < n; i++) scanf("%I64d", &a[i]);    sort(a, a + n);    for(int i = 0; i < n; i++)        for(int j = 1; j <= 31; j++){            ll tmp = p[j] - a[i];            if(tmp > 0) ans += upper_bound(a + i + 1, a + n, tmp) - lower_bound(a + i + 1, a + n, tmp);        }        printf("%I64d\n", ans);    }    return 0;}
1 0
原创粉丝点击