codeforence 251A:(二分)
选出三个数,让最大的数和最小的数之差不超过d~
那只需要将所有数排序后,找出<=(最小数+d)的数的位置,之间的数都能进行选择
#include"cstdio" #include"cstring" #include"algorithm" #define MAXN 100005 using namespace std; long long num[MAXN]; long long tail; long long find(long long n) { long long low=0,high=tail-1,mid; while(high>=low) { mid=low+(high-low)/2; if(num[mid]==n) return mid; else if(num[mid]>=n) high=mid-1; else low=mid+1; } return low-1; } int main() { long long d,n,ans; while(scanf("%lld %lld",&n,&d)!=EOF) { tail=0; ans=0; for(long long i=0;i<n;i++) scanf("%lld",&num[i]); for(int i=0;i<n;) { int k=i+1; while(num[i]==num[k]&&k<n) k++; num[tail++]=num[i]; i=k; } sort(num,num+tail); for(long long i=0;i<tail;i++) { long long p=find(d+num[i])-i-1; ans+=(1+p)*p/2; } printf("%lld\n",ans); } return 0; }