分析
70%数据: n2预处理两个数的和,再枚举,因为每一个元素值比较小,开一个数组来存储是否存在。
100% :因为数值比较大,所以考虑用哈希定位然后判断。每次输入都判断编号比他小的两个数的和是否符合条件,看看这个数是不是好元素。
然后将它加进去与前面的值求出新的几组和,供下面的数判断。
注意哈希有关函数insert,locate,find
上代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;
const int hash=25000003;
const int c=889734817;
int n,a[6001],ans,cnt,ha[hash],pd;
int locate(int x)//定位,加上一个大数可以防负数
{
int t=(x%hash+hash)%hash;
int i=0;
while(i<hash&&ha[(t+i)%hash]!=x&&ha[(t+i)%hash]!=c) i++;
return (t+i)%hash;
}
void insert(int x)//定好位置赋值
{
int y=locate(x);
ha[y]=x;
}
bool find(int x)//查询
{
return ha[locate(x)]==x;
}
int main()
{
freopen("good.in","r",stdin);
freopen("good.out","w",stdout);
cin>>n;
for(int i=0;i<hash;i++) ha[i]=c;
for(int i=1;i<=n;i++)
{
cin>>a[i];
for(int j=1;j<i;j++)//每一个都枚举到i-1
{
if(find(a[i]-a[j]))
{
ans++;
break;
}
}
for(int j=1;j<=i;j++)//加上i之后的几组和
{
insert(a[i]+a[j]);
}
}
cout<<ans;
return 0;
}