很显然,题目中给出的计算方式(A-B=C),A,B都是未知的,所以唯一的做法是对其中一个数字在给出的数串当中进行枚举,C是唯一确定的,所以枚举每一位数时对应的匹配数也是对应的,只需要查找这个对应数在给出数据当中是否存在,则就让我们联想到了HASH匹配。
由于题目中告诉条件(不同位置的数字一样的数对算不同的数对),所以对每个数进行HASH时需要储存它出现的次数(下面用struct实现)。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<ctime>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdlib>
#define N 1400000
#define ma1 1000000007
#define ma2 317
using namespace std;
struct node{
int num,cou;
};
int num[N],n,c;
node hash[N];
int loca(int x)
{
int temp=x;
x=x*ma2%ma1;
return x;
}
int main()
{
freopen("dec.in","r",stdin);
freopen("dec.out","w",stdout);
for(int i=1;i<=N;++i)
{
hash[i].num=0;
hash[i].cou=0;
}
long long ans=0;
scanf("%d%d",&n,&c);
for(int i=1;i<=n;++i)
{
scanf("%d",&num[i]);
hash[num[i]].num=loca(num[i]);
hash[num[i]].cou++;
}
for(int i=n;i>=1;--i)
{
int temp=num[i]-c;
if(hash[temp].num==loca(temp)&&temp>0)
{
ans+=hash[temp].cou;
}
}
cout<<ans;
return 0;
}
最好 取2个MAGIC数,最后IF条件句要特判一下temp>0。