首页 > 其他 > 详细

洛谷 SP297 【AGGRCOW - Aggressive cows】

时间:2020-04-25 13:02:14      阅读:38      评论:0      收藏:0      [点我收藏+]

原题连接:https://www.luogu.com.cn/problem/SP297

题目描述

Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don‘t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ wants to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?

输入格式

t – the number of test cases, then t test cases follows.
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi

输出格式

For each test case output one integer: the largest minimum distance.

题意翻译

好斗的奶牛

题目描述: 农夫约翰搭建了一间有N间牛舍的小屋。牛舍排在一条线上,第i号牛舍在Xi的位置。但是他的M头牛对小屋很不满意,因此经常相互攻击。约翰为了防止牛之间相互伤害,因此决定把每头牛都放在离其他牛尽可能远的牛舍。求最近的两头牛之间距离的最大值。

输入格式: t – 表示有t组数据,每组数据都由下面格式的数据构成。

  • 第1行: 两个用空格隔开的整数: N和C
  • 第2到n+1行: 每行一个整数xi

输出格式: 每组输出一个整数: 最近两头牛之间距离的最大值.

输入输出样例

输入 
1
5 3
1
2
8
4
9
输出 
3
 
 
解题思路:二分答案

跟跳石子类似

不过难度比跳石子低 所以过了跳石子的应该很容易可以过这个题

之后附上我的跳石子的check函数跟本题的check函数比较一下

这个是跳石头的:

bool check(int mid){
int cnt=0,last=0;
for(int i=1;i<=n;i++)
    if(f[i]-last<mid)
        cnt++;
    else last=f[i];
if(cnt>m) return false;
else return true;
}

 

这个是本题的:

bool check(int mid){
int cnt=0,last=x[1];
for(int i=2;i<=n;i++){
    if(x[i]-last>=mid){
        cnt++;
        last=x[i];
    }
}
if(cnt>=m-1)return true;
else return false;
}

 

不同的地方就是在last的值变换以及 cnt跟m比较后的返回 是true还是false, 因为跳石子有一个m的上限所以如果cnt超了上限就返回false 而 本题cnt不能比m小,如果小就返回false

之后附上我本题的完整代码,供大家参考

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int x[100100];
int n,m;
int maxn=0;
bool check(int mid){
    int cnt=0,last=x[1];
    for(int i=2;i<=n;i++){
        if(x[i]-last>=mid){
            cnt++;
            last=x[i];
        }
    }
    if(cnt>=m-1)return true;
    else return false;
}
int main(){
    int T;
    cin>>T;
    while(T--){
    memset(x,0,sizeof(x));
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>x[i];
    }
    sort(x+1,x+1+n);
    int l=0,r=1000000000;
    for(int i=1;i<=n;i++){
        int mid;
        while(l<r){
            mid=(l+r+1)/2;
            if(check(mid)){
                maxn=mid;
                l=mid;
            }
            else r=mid-1;

        }
    }
        cout<<maxn<<endl;
    }
        return 0;
}
 

 

洛谷 SP297 【AGGRCOW - Aggressive cows】

原文:https://www.cnblogs.com/caigeshuizhale-4126/p/12772364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!