Educational Codeforces Round 64 -C(二分)

题目链接:https://codeforces.com/contest/1156/problem/C

题意:给出n个数和整形数z,定义一对数为差>=z的数,且每个数最多和一个数组成对,求最多有多少对。

思路:先按升序排序,在区间[0,n/2]二分答案即可,判断m是否满足条件利用贪心思想,即看前x个数和后x个数是否能对应组成对。

AC代码:

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

int n,z,a[200005];

bool judge(int x){
    bool ans=true;
    for(int i=0;i<x;++i)
        if(a[i]+z>a[n+i-x]){
            ans=false;
            break;
        }
    return ans;
}

int main(){
    scanf("%d%d",&n,&z);
    for(int i=0;i<n;++i)
        scanf("%d",&a[i]);
    sort(a,a+n);
    int l=0,r=n/2,m;
    while(l<=r){
        m=(l+r)>>1;
        if(judge(m)) l=m+1;
        else r=m-1;
    }
    printf("%d\n",r);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/FrankChen831X/p/10808943.html