CF Edu 15 B 求和二的幂次

来源:互联网 发布:co.nz 域名查询 编辑:程序博客网 时间:2024/05/16 08:29

题目连接

http://codeforces.com/contest/702/problem/B

Description

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.

Sample Input

4
7 3 2 1

Sample Output

2

题意

给你一堆数,问在这堆数中两两组合,使他们的和是二的幂次的最多的组合数

题解

开始我就想直接每个数依次和其他数求和然后用(x&x-1)判断是否是二的幂次,发现T了…果断就不知道怎么优化了QAQ…看了题解,发现求组合的时候没有一个一个挨个去求,2^32是大于1e9的,n^2的复杂度,内层用2的幂次单独判断,用map处理每个数出现的次数。最后+1,那开始时候的判断就只会判断已经加入map中的数,而不会出现一个数与其他所有数比较的情况。
还有就是左移右移又记反了,x<

代码

#include<bits/stdc++.h>using namespace std;//long long a[100005];bool fun(long long v){    bool flag = 0;    if((v>0)&&(v&(v-1))==0)        flag = 1;    return flag;}map<long long ,long long>s;int main(){    int n;    scanf("%d",&n);    long long ans=0;    for(int i=0;i<n;i++)    {       // scanf("%I64d",&a[i]);       long long t;       scanf("%I64d",&t);        for(int j=0;j<32;j++)        {            ans+=s[(2<<j)-t];        }        s[t]++;    }    printf("%I64d",ans);    return 0;}
0 0
原创粉丝点击