POJ 2456 Aggressive cows

来源:互联网 发布:淘宝卡dnf称号 编辑:程序博客网 时间:2024/04/30 09:04

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 want 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?
Input
* Line 1: Two space-separated integers: N and C 

* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
* Line 1: One integer: the largest minimum distance
Sample Input
5 312849
Sample Output
3
Hint
OUTPUT DETAILS: 

FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3. 

Huge input data,scanf is recommended.

这道题的意思就是农夫有n个stuff,如果一个stuff里面有两头牛他们就会打架,所以我们尽可能分开它们,而且要尽量远,农夫想知道分开它们后各两头牛距离之中最小值是多少。

这道题,不会。。。于是搜题解,文字题解,看不懂。。。于是看代码,于是懂了。

思路就是,先把各个stuff排序一下,这样我就知道最大最小的距离了,而且我们要在这个距离之内将stuff分成c-1份,所以最大距离dis就是(stuff[n - 1] - stuff[0]) / (c - 1)。两头牛之间的距离平均下来不可能比这个更大了,也就是我们要求的最小值MIN不可能大于这个数字了。比如1 3 5分三头牛,那dis = 2,这是刚好的,如果是1 2 5,那么答案其实是在(0,2)之间产生的,这也就是这道题用二分的思路。二分的操作,无异于left = mid+ 1,right = mid - 1,一直二分下去看看哪个dis恰好不满足(比如1 3 5,第一步操作后left = 3,然后在3 到 5 之间二分,变成[3,3]),那么left - 1就是满足的了。

代码:

#include<iostream>#include<algorithm>#include<cstdio>using namespace std;int stuff[1000005], dval[1000005], n, c;bool Find(int mid){int tmp = 0, cnt = 0;for(int i = 0; i < n - 1; i++){tmp += dval[i];if(tmp >= mid){cnt++;tmp = 0;}}if(cnt >= c - 1)return 1;return 0;}int main(){int left, right, mid;cin >> n >> c;for(int i = 0; i< n ; i++)scanf("%d", &stuff[i]);sort(stuff, stuff + n);for(int i = 0; i < n - 1; i++)dval[i] = stuff[i + 1] - stuff[i];left = 0;right = (stuff[n - 1] - stuff[0]) / (c - 1);while(right - left > 1){mid = (right + left) / 2;if(Find(mid))left = mid;elseright = mid;}if(Find(right))cout << right << endl;elsecout << left << endl;return 0;}


0 0
原创粉丝点击