codeforces Educational Codeforces Round 64 (Rated for Div. 2) C (水题 暴力可过)

C. Match Points
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
4 2
1 3 3 7
outputCopy
2
inputCopy
5 5
10 9 5 8 7
outputCopy
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).

 

题意:很简单。

思路:一开始我以为差最小的匹配就行,然后发现不对。例如:4 2 1 3 6 7,就过不了。慢慢的发现,先排个序,然后用半部分的数匹配后半部分的数,这就是最优的。然后每一次都二分一个满足条件的下标,但要保证下标要 >= mid,暴力找到第一个没用过的数,匹配上就行。

AC代码:

#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define INT(t) int t; scanf("%d",&t)

using namespace std;

const int maxn = 2e5 + 10;
int x[maxn],vis[maxn];

int main() {
    int n,z;
    while(~scanf("%d%d",&n,&z)){
        for(int i = 1;i <= n;++ i)
            scanf("%d",&x[i]);
        sort(x + 1,x + 1 + n);
        clr(vis,0);
        int ans = 0,mid = (n + 1 + (n % 2 == 0)) / 2;
        //debug(mid);
        for(int i = 1;i <= n;++ i){
            if(vis[i]) continue;
            int pos = lower_bound(x + 1,x + 1 + n,x[i] + z) - x;
            //debug(pos);
            if(pos == n + 1) continue;
            for(int j = (pos >= mid ? pos : mid ++);j <= n;++ j)
                if(!vis[j]){
                    vis[i] = vis[j] = 1;
                    ++ ans;
                    break;
                }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值