51Nod 2654 最小距离最大 c/c++ 题解

题目描述

给出n个位置,从中选出k个,让这k个位置相邻两个之间的距离尽可能的大,尽可能大的意思是这k-1个距离的最小值尽量大。输出这个最大的最小值。
样例解释:选位置:1 5 9。
输入
第一行:2个数n和k(2 <= n <= 100000, 2 <= k <= 10000, k <= n)
后面n行:每行一个数Pi,表示具体位置(0 <= Pi <= 10^9),位置是无序的。
输出
输出一个数,对应最大的距离。
输入样例
5 3
1
3
5
7
9
输出样例
4

题解:

要找出一个尽可能大的距离(1),而且还有满足这个距离是从n个数中选出的 k个数中的 k-1个距离中的最小距离(2)
第1点的解决方法
枚举距离,可以是O(n)的直接枚举,也可以是O(logn)的二分枚举,先看看后面的时间复杂度再来确定用哪一个。
第2点的解决方法
从枚举那里得到的一个距离x,要判断这个距离x是不是k个数中的最小距离,就是看能不能以x为最小距离看能不能从n个数当中抽出k个数(或者>k个数),这里我也不是很理解【待理解】
这道题目在POJ在有一道相关题目 - 题解

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n,k;
int p[MAX];

bool check(int x)
{
    int cnt = 1;
    int s = p[0];
    for(int i = 1; i < n; i++)
    {
        if(p[i] - s >= x)// ">="的原因是x只是最小距离
        {
            cnt++;
            s = p[i];
        }
    }
    if(cnt >= k)// ">="的原因是大于k个数也可以
    {
        return true;
    }
    else
    {
        return false;
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    while(cin >> n >> k)
    {
        for(int i = 0; i < n; i++)
        {
            cin >> p[i];
        }
        sort(p,p+n);
        int l = 0;
        int r = p[n-1] - p[0];
        int res;
        while(l <= r)
        {
            int mid = (l+r)/2;
            if(check(mid))
            {
                res = mid;
                l = mid + 1;
            }
            else
            {
                r = mid - 1;
            }
        }
        cout << res << endl;
    }
    return 0;
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值