微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Educational Codeforces Round 64 (Rated for Div. 2)-C. Match Points

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,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).

 

 题目:http://codeforces.com/contest/1156/problem/C

 

题意 : 长度为n的数组, 选择两个数,要求|差值| >= k, 但是被选择过的数不允许被再次选择,问 最大的匹配对数。

在一开始,我想用尺选法+标记数组来求解这个问题,但是卡在了第七个数据上,这组数据的n是200000,正确答案是100000,而我输出了9913,小于正确答案。

我就很困惑,直到看到别人博客里的一组数据  n = 4,k = 4  arr =  {4 8 9 12} 这组数据用我一开始的程序来算的话是 1 而正确答案是2

 

 

尺选法+标记数组 WA on test7

分享图片

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 2e5+5;
int arr[maxn];
int vis[maxn]={};
int main(){
    int n,k;
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;i++)
        scanf("%d",&arr[i]);
    sort(arr,arr+n);
    int cnt = 0;
    int i=0,j=0;
    while(j<n){
        while(arr[j]-arr[i] < k && j<n)j++;
        if(j>=n)break;
        vis[j] = 1;
        j++;
        cnt++;
        i++;
        while(vis[i] && i<n)i++;
    }
    printf("%d\n",cnt);
    return 0;
}
View Code

 

AC代码

分享图片

#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn = 2e5+5;
int arr[maxn];

int main(){
    int n,j=n/2;
    for(;i<n/2;i++){
        for(;j<n;j++){
            if(arr[j]-arr[i]>=k){
                cnt++;j++;
                break;
            }
        }
    }
    printf("%d\n",cnt);
    return 0;
}
View Code

 

 

还可以二分做,

链接https://blog.csdn.net/pythonbanana/article/details/89786072

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。