A-B 数对
先将数列排序,A-B=C可以看成A=B+C,只要用二分把A的首位和末尾找到,A的个数就是差值+1,最后把每个数都求一遍就是答案了
`#include<stdio.h>
include<stdlib.h>
include<string.h>
include<bits/stdc++.h>
using namespace std;
int seek(int n,long long *lst,long long x){
int l=0,r=n-1;
while(l<=r){
int m=(l+r)/2;
if(lst[m]>=x) r=m-1;
else l=m+1;
}
return l;
}
int seek2(int n,long long *lst,long long x){
int l=0,r=n-1;
while(l<=r){
int m=(l+r)/2;
if(lst[m]>x) r=m-1;
else l=m+1;
}
return r;
}
int main(){
int n;
long long c,sum=0;
scanf("%d %lld",&n,&c);
long long lst[200007];
for(int i=0;i<n;i++){
scanf("%lld",&lst[i]);
}
sort(lst,lst+n);
for(int i=0;i<n;i++){
long long x=lst[i]+c;
if(x>lst[n-1]) break;
int p=seek(n,lst,x);
sum+=seek2(n,lst,x)-p+1;
}
printf("%lld",sum);
return 0;
} `
学习总结:一定要开long long啊,不开long long见祖宗,十年oi一场空。
浙公网安备 33010602011771号