您的位置:首页 > 其它

CodeForces 702B: Powers of Two(遍历、穷举)

2017-07-15 11:14 656 查看
Powers of Two

time limit per test: 3 seconds

memory limit per test: 256 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.

Simple Input

4
7 3 2 1
3
1 1 1


Simple Output

2
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.

Code 1

思路:遍历查找

//时间复杂度太高,当输入数据组数较多时会超时
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
#define maxn 100005
LL a[maxn]={0};

int main()
{
int n;
while(~scanf("%d",&n))
{
int sum=0;
for(int i=0; i<n; i++)
scanf("%lld",&a[i]);
for(int i=0; i<n-1; i++)
for(int j=i+1; j<n; j++){
LL x=1;
for(int k=0; k<=31; k++)
{
if(a[i]+a[j]==x) {sum++;break;}
x=x<<1;
}
}
printf("%d\n",sum);
}
return 0;
}


Code 2

思路:利用ai+aj=2x关系枚举x

#include<bits/stdc++.h>
using namespace std;
#define LL long long
map<LL,int>a;           //映射到int的初始值是零
LL sum=0;

int main()
{
int n;
while(~scanf("%d",&n)){
for(int i=0; i<n; i++)
{
LL x;
scanf("%lld",&x);
for(int j=0; j<=31; j++)
sum+=a[(1LL<<j)-x];     //由ai+aj=2^x枚举x,若对应LL非空,则加上其映射值int
a[x]++;                     //用int记录对应LL出现的次数
}
printf("%lld\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: