P1102

题目传送门:P1102

很简单的小小橙题~

首先数字在数组中的位置不影响答案,所以直接排个序方便后面操作。

其次,对于数组中的某个数x,如果x+c也在数组里,且x在数组里出现了cnt[x]次,x+c出现了cnt[x+c]次,那么根据小学二年级就学过的乘法原理,x和x+c对答案的贡献就是cnt[x]*cnt[x+c]

那我们把数组中所有数出现的次数给记录下来,并且遍历数组中所有种类的数(可以对原数组去重),累加贡献就好了。

代码:

点击查看代码
#include<bits/stdc++.h>
#define int long long
using namespace std; 

const int N=2e5+5;
const int inf=1e15;
int n,c,a[N],b[N],ans;
map<int,int> mp;//由于a[i]比较大,所以用map充当一个桶,相当于cnt 

signed main(){
	scanf("%lld%lld",&n,&c);
	for(int i=1;i<=n;i++){
		scanf("%lld",&a[i]);
		b[i]=a[i];
		mp[a[i]]++;//统计次数 
	}
	sort(b+1,b+n+1);
	int len=unique(b+1,b+n+1)-b-1;//去重 
	for(int i=1;i<=len;i++){
		if(mp[b[i]+c]){//可以构成A-B=C数对 
			ans=ans+mp[b[i]]*mp[b[i]+c];//累加贡献 
		}
	}
	printf("%lld",ans);
	return 0;
}
posted @ 2025-07-08 11:42  qwqSW  阅读(11)  评论(0)    收藏  举报