Ashish有一个集合A,里面有n个正整数,配对规则如下:对于 | a[i] - a[j] | >= z,则 i 和 j 配对,每个数只能配对一次。求最大配对数。
Input
第一行输入两个正整数n和z。2<=n<2e5,1<=z<=1e9
第二行输入n个正整数 1<=ai<=1e9
Output
输出一个正整数,最多有多少对数字能够匹配
Examples
Input
4 2
1 3 3 7
Output
2
Input
5 5
10 9 5 8 7
Output
1
error1:lower_bound()
error exp: 4 2 1 3 4 5 answer: 2 Myoutput: 1
最后看题解:发现这个情况不够准确,同时答案最大是n/2个,用整数二分(双指针)可以做对。
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 200021;
long long a[N];
bool st[N];
int main()
{
int n,z; cin>>n>>z; int ans = 0;
for(int i = 0; i < n; ++i) cin>>a[i];
sort(a, a+ n);
// 对 1 2 45 46 这类数组来说,也是可以的;
int le = 0, ri = (n+1)/2;
while(le <= n && ri <= n) {
if(a[ri] - a[le] >= z) ans++, le++;
ri++;
}
cout<<ans;
}```