题解:AT_abc463_d [ABC463D] Maximize the Gap

· · 题解

经典套路。

考虑二分最小距离,贪心的选择尽可能多的布,先给所有布按右端点排序,每次二分一个 x,遍历每块布,如果和上一块布的距离 \ge x,就直接选更新最小值。

合法条件是选的布数量 \ge k。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<ll,ll>
#define dgd priority_queue<ll>
#define xgd priority_queue<pii,vector<pii>,greater<pii>>
#define fi first
#define se second
#define pbk push_back
#define all(_c) _c.begin(),_c.end()
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define nl cout << "\n"
const int INF=1e9;
const ll Inf=4e18;
const int abc=26;
const double pi=3.1415926;
int read(){
    int x=0,f=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-') f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-48;c=getchar();}
    return x*f;
}
ll n,k;
struct st{
    ll l,r;
}s[200010];
bool cmp(st a,st b){
    return a.r<b.r;
}
bool check(ll x){
    ll cnt=0,lst=-Inf;
    for(int i=1;i<=n;i++){
        if(s[i].l-lst>=x){
            cnt++;
            lst=s[i].r;
        }
    }
    return cnt>=k;
}
void solve(){
    cin >> n >> k;
    for(int i=1;i<=n;i++){
        cin >> s[i].l >> s[i].r;
    }
    sort(s+1,s+n+1,cmp);
    ll left=1,right=Inf,ans=-1;
    while(left<=right){
        ll mid=(left+right)>>1;
        if(check(mid)){
            ans=mid;
            left=mid+1;
        }else{
            right=mid-1;
        }
    }
    cout << ans;
    nl;
    return;
}
int main(){
    ios::sync_with_stdio(false);
    cout.tie(0),cin.tie(0);
    int t=1;
    while(t--) solve();
    return 0;
}