A-B 数对 - 题目 - Daimayuan Online Judge
题意:
给出一串数以及一个数字 C ,要求计算出所有 A−B=C 的数对的个数(不同位置的数字一样的数对算不同的数对)。
思路:
首先n方枚举一定超时,因此我们二分即可,O(nlogn)
注意到,数字可能会重复,因此我们预先统计一下每个数字的个数,然后排序去重,二分的同时乘上个数即可
Code:
#include <bits/stdc++.h>
using namespace std;
const int mxn=2e5+10;
int n,c,ans=0;
int a[mxn];
unordered_map<int,int> mp;
int main(){
scanf("%d%d",&n,&c);
for(int i=1;i<=n;i++) scanf("%d",&a[i]),mp[a[i]]++;
sort(a+1,a+1+n);
int len=unique(a+1,a+1+n)-a-1;
for(int i=1;i<=len;i++){
int pos1=lower_bound(a+1,a+1+len,a[i]+c)-a;
//int pos2=lower_bound(a+1,a+1+len,a[i]-c)-a;
if(a[pos1]==a[i]+c) ans+=mp[a[pos1]]*mp[a[i]];
//if(a[pos2]==a[i]-c) ans+=mp[a[pos2]]*mp[a[i]];
}
printf("%d\n",ans);
return 0;
}