POJ2456-Aggressive cows

题目链接:点击打开链接

Description

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 3
1
2
8
4
9

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.

题意:就是从0 - 1000000000长度中,找一个最大的能满足把所有奶牛,放入给定的房间里的那个长度;

思路:二分。从整体长度二分。每确定一个mid就去给定区间里 看满足不满足 能把所有奶牛放进去。 满足的话,记录下来,最后输出最大的那个。

AC代码:


#include<iostream>
#include<queue>
#include<algorithm>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<cstdio>
#include<cstdlib>
#include<cctype>
#include<cstring>
using namespace std;
const int MAX = 1000000010;
const int INF = 0X3f3f3f;
typedef long long LL;
int main() {
	int n, m;
	while(scanf("%d %d", &n, &m) != EOF) {
		int x;
		vector<int> t;//存给定的房间
		vector<int> tt;//存 满足的mid
		while(n--) {
			scanf("%d", &x);
			t.push_back(x);
		}
		LL l = 0, r = MAX;//用longlong 防止爆
		sort(t.begin(), t.end());//从题目中可以看得出来 得先排序
		while(l <= r) {//二分
			LL mid = l + (r - l)/2;
			int j = 1, flag = 0, k = 0;
			if(mid > *max_element(t.begin(), t.end())) {//如果mid 比 给定房间的最大值 还大 ,直接缩小范围
				r = mid - 1;
				continue;
			}
			for(int i = 2; i <= m; i++) {//因为第一个肯定放在t[0], 所以从第二头牛开始
				for(; j < t.size(); j++) {//遍历房间
					if(t[k] + mid <= t[j]) {//在这个房间的基础上,+ mid 直到找到第一个 满足的 。
						flag++;//表示这头奶牛可以处理掉
						k = j;//那么下次要从这个位置往后面加mid 
						break;
					}
				}
			}
			if(flag == m -1) {//是否能安排完所有的奶牛 注意m-1
				tt.push_back(mid);
				l = mid + 1;//因为找最大的,所以要把mid变大,再去试试。
			} else if(flag < m-1) {//说明mid太大
				r = mid - 1;
			} else l = mid + 1;//说明mid太小
		}
		cout << *max_element(tt.begin(), tt.end()) << endl;//输出所有满足中最大的那个
	}
	return 0;
}
原文地址:https://www.cnblogs.com/ACMerszl/p/9572994.html