C.Match Points
You are given a set of points x1, x2, …, xn on the number line.
Two points i and j can be matched with each other if the following conditions hold:
neither i nor j is matched with any other point;
|xi−xj|≥z.
What is the maximum number of pairs of points you can match with each other?
Input
The first line contains two integers n and z (2≤n≤2⋅105, 1≤z≤109) — the number of points and the constraint on the distance between matched points, respectively.
The second line contains n integers x1, x2, …, xn (1≤xi≤109).
Output
Print one integer — the maximum number of pairs of points you can match with each other.
Examples
Input
4 2
1 3 3 7
Output
2
Input
5 5
10 9 5 8 7
Output
1
Note
In the first example, you may match point 1 with point 2 (|3−1|≥2), and point 3 with point 4 (|7−3|≥2).
In the second example, you may match point 1 with point 3 (|5−10|≥5).
题解:
对数组从小到大排序
二分答案mid,
check是判断数组重前mid个数能否和数组中的后mid个匹配
ps:
为啥可以这样暂时还没懂,先挂着
code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
#define int long long
const int maxm=2e5+5;
int a[maxm];
int n,k;
bool check(int mid){
for(int i=1;i<=mid;i++){
if(a[n-mid+i]-a[i]<k){
return 0;
}
}
return 1;
}
signed main(){
cin>>n>>k;
for(int i=1;i<=n;i++){
cin>>a[i];
}
sort(a+1,a+1+n);
int ans=0;
int l=0,r=n/2;
while(l<=r){
int mid=(l+r)/2;
if(check(mid)){
ans=mid;
l=mid+1;
}else{
r=mid-1;
}
}
cout<<ans<<endl;
return 0;
}