其他分享
首页 > 其他分享> > 愤怒的牛

愤怒的牛

作者:互联网

题目描述

思路

思路

#include <cstdio>

const int inf = 0x3f3f3f3f;
int n, m, ans, L = inf, R = 0, arr[100005];
inline int read() {
    int s = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    return s * f;
}
void qsort(int L, int R) {
    int l = L, r = R;
    int mid = arr[l + r >> 1], tmp;
    while (l < r) {
        while (arr[l] < mid) l++;
        while (arr[r] > mid) r--;
        if (l <= r) {
            tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            l++, r--;
        }
    }
    if (L < r) qsort(L, r);
    if (l < R) qsort(l, R);
}

int main() {
    n = read(), m = read();
    for (int i = 1; i <= n; ++i) arr[i] = read();
    qsort(1, n);
    int l = 1, r = arr[n];
    while (l <= r) {
        int mid = l + r >> 1, cnt = 0, pre;
        for (int i = 1; i <= n; ++i) {
            if (i == 1) {
                cnt = 1; pre = arr[1];
            } else if (arr[i] - pre >= mid){
                pre = arr[i], cnt++;
            }
        }
        if (cnt >= m) {
            ans = mid; l = mid + 1;
        } else r = mid - 1;
    }
    printf("%d\n", ans);
    return 0;
}

标签:arr,ch,int,mid,while,ans,愤怒
来源: https://www.cnblogs.com/liuzz-20180701/p/11563668.html