Codeforces 702B【二分】

题意:
给一个a数组,输出有多少对相加是等于2^x的。1<=a[i]<=1e9,n<=1e5
思路:
a[i]+a[j]=2^x 对于每个a[i],枚举x,然后二分查找a[j];
ps:
①:数组大的简单题,基本上就是二分这种降低复杂度;
②:对于a+b=c,三个对象都有考虑的意义;

加一发挫code……

#include<cstdio>
#include<iostream>
#include<queue>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define eps 1e-8
typedef __int64 LL;


const int N=1e5+10;
int a[N];

int t[35];
void init()
{
    for(int i=0;i<31;i++)
        t[i]=1<<i;
}

int main()
{
    init();
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
    sort(a,a+n);

    int temp,s,e,mid;
    LL ans=0;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<31;j++)
        {
            temp=t[j]-a[i];
            if(temp<1||temp>1e9)
                continue;
            s=lower_bound(a+i+1,a+n,temp)-a;//第一个等于temp的位置;
            e=upper_bound(a+i+1,a+n,temp)-a;//大于temp的位置;
            ans+=e-s;
        }
    }
    printf("%lld\n",ans);
    return 0;
}

其实更好利用那个等式a+b=c;
我们可以直接标记数组元素的个数,然后中间直接操作。

再加一发挫code…….

#include<cstdio>
#include<iostream>
#include<map>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define eps 1e-8
typedef __int64 LL;

map<int,int>cnt;

int main()
{
    LL ans=0;
    int n;
    int x,t;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&t);
        for(int j=0;j<31;j++)
        {
            x=1<<j;
            if(x>t)
                ans+=cnt[x-t];
        }
        cnt[t]++;
    }
    printf("%I64d\n",ans);
    return 0;
}

转载于:https://www.cnblogs.com/keyboarder-zsq/p/5934888.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值