Codeforces 702B. Powers of Two

题目连接:http://www.codeforces.com/problemset/problem/702/B
题意:给定n个数,判断有多少个数对(i, j)满足存在x且 ai+aj=2x 。其中 1n105 , 1ai109
想法:由于 1ai109 ,故我们可枚举x,再查询 2xai 是否存在。其中查询过程可二分,所以复杂度为 O(32nlogn) ,若我们记录下最大两个数的和,那么可进一步优化到 O(dnlogn) ,其中 d=log(an1+an2)
代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>

typedef long long ll;
const int MAXN = 100000 + 10;
int a[MAXN];

int main(){
    std::ios::sync_with_stdio(false);
    int n;
    while(std::cin >> n){
        for(int i = 0; i < n; ++i){
            std::cin >> a[i];
        }
        if(n == 1){
            puts("0");
            continue;
        }
        std::sort(a, a + n);
        ll ans = 0;//可能会超int
        int k = log(a[n - 1] + a[n - 2]) / log(2) + 1;
        for(int i = 0; i < n; ++i){
            for(int j = 0; j <= k; ++j){
                int t = (1 << j) - a[i];
                if(t > 0){
                    int l = std::lower_bound(a + i + 1, a + n, t) - a;
                    int r = std::upper_bound(a + i + 1, a + n, t) - a;
                    if(r > l){
                        ans += r - l;
                    }
                }
            }
        }
        std::cout << ans << std::endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值