POJ 2456 Aggressive cows 二分 贪心

本文提供了一道经典的算法题——POJ 2456的解题思路及C++代码实现。该题要求在给定的位置中放置指定数量的元素,并使相邻元素间的最小距离最大化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  题目链接: http://poj.org/problem?id=2456

  题目描述: 给你N个位置, 让你在这些位置中放M个元素, 使得其中最小的距离最大化

  解题思路: 最小值最大化的问题一般都是二分吧, 要掌握好边界条件, 要写好OK函数.....

  代码: 

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iterator>
#include <cmath>
#include <algorithm>
#include <stack>
#include <deque>
#include <map>
#include <set>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
#define mem0(a) memset(a,0,sizeof(a))
#define sca(x) scanf("%d",&x)
#define de printf("=======\n")
typedef long long ll;
using namespace std;
const int INF = 1e9+5;
const int maxn = 1e5+10;
int x[maxn];
int n, m;

int ok( int num ) {
    int temp = m-1;
    int cnt = 0;
    for( int i = 1; i < n; i++ ) {
        if( x[i]-x[cnt] >= num ) {
            temp--;
            cnt = i;
        }
    }
    if( temp <= 0 ) return 1;
    else return 0;
}

void solve() {
    int low = 0;
    int high = INF;
    while( high - low > 1 ) {
        int m = (low+high) >> 1;
        if( ok(m) ) {
            low = m;
        }
        else {
            high = m;
        }
    }
    printf( "%d\n", low );
}

int main() {
    while( scanf( "%d%d", &n, &m ) == 2 ) {
        for( int i = 0; i < n; i++ ) {
            sca( x[i] );
        }
        sort(x, x+n);
        solve();
    }
    return 0;
}
View Code

  思考: 这题没啥的吧, 今天去面试了...... 很难受, 像死一样,进入复试和老板谈话的时候我感觉整个世界都在旋转一样, 倒不是因为紧张, 是感觉自己实在是很虚, 学校的老师会看你的潜力, 而公司的老板只会看你现在是不是有价值, stupid, 还有一些面试的技巧需要我去学习, 去看看明天的橘子娱乐吧.....我一定要加油啊!!!

转载于:https://www.cnblogs.com/FriskyPuppy/p/7486987.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值