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;
}

本文介绍了一个算法问题,即找出所有整数对 (i, j),使得 a[i] + a[j] 是2的幂次。提供了两种解决方案:遍历查找法和使用哈希映射优化时间复杂度的方法。
293

被折叠的 条评论
为什么被折叠?



