题目描述
You are given a set of points x1x1, x2x2, …, xnxn on the number line.Two points ii and jj can be matched with each other if the following conditions hold:neither ii nor jj is matched with any other point;|xi−xj|≥z|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 nn and zz (2≤n≤2⋅1052≤n≤2⋅105, 1≤z≤1091≤z≤109) — the number of points and the constraint on the distance between matched points, respectively.The second line contains nn integers x1x1, x2x2, …, xnxn (1≤xi≤1091≤xi≤109).
Output
Print one integer — the maximum number of pairs of points you can match with each other.
ExamplesInput
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 11 with point 22 (|3−1|≥2|3−1|≥2), and point 33 with point 44 (|7−3|≥2|7−3|≥2).In the second example, you may match point 11 with point 33 (|5−10|≥5|5−10|≥5).
错误思路
从第一个开始二分找a[i]+z。
错误代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <bits/stdc++.h>
int vis[200005]={0};
long long a[200005];
using namespace std;
int main(){
int n,t;
scanf("%d%d",&n,&t);
for(int i = 0;i < n;i++)scanf("%lld",&a[i]);
sort(a,a+n);
int cnt = 0;
for(int i = 0;i < n;i++){
int k=lower_bound(a+i,a+n,a[i]+t)-a;
if(!vis[i]&&!vis[k]&&k<n){
vis[k]=1;
vis[i]=1;
cnt++;
}
}
cout << cnt << endl;
// printf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC);
return 0;
}
为什么错了呢?因为 4 2 1 3 4 5 这组数据就过不了。
换个思路,最多的匹配数是n/2,不妨从中间找和第一个匹配的。写起来有点像尺取。
ac代码
#include <iostream>
#include <algorithm>
using namespace std;
long long a[200005];
int main(){
int n;
long long z;
cin >> n >> z;
for(int i = 1; i <= n;i++)scanf("%lld",&a[i]);
sort(a+1,a+n+1);
int l = 1,r = (n+1)/2+1;
long long cnt = 0;
while(l<=n&&r<=n){
if(a[r]-a[l]>=z)cnt++,l++;
r++;
}
cout << cnt << endl;
}
好题,,如果我当时打了这场这题很大概率过不了hhh