总时间限制:
1000ms
内存限制:
65536kB
描述
农夫约翰是一个精明的会计师。他意识到自己可能没有足够的钱来维持农场的运转了。他计算出并记录下了接下来 N (1 ≤ N ≤ 100,000) 天里每天需要的开销。
约翰打算为连续的M (1 ≤ M ≤ N) 个财政周期创建预算案,他把一个财政周期命名为fajo月。每个fajo月包含一天或连续的多天,每天被恰好包含在一个fajo月里。
约翰的目标是合理安排每个fajo月包含的天数,使得开销最多的fajo月的开销尽可能少。
输入
第一行包含两个整数N,M,用单个空格隔开。
接下来N行,每行包含一个1到10000之间的整数,按顺序给出接下来N天里每天的开销。
输出
一个整数,即最大月度开销的最小值。
样例输入
7 5
100
400
300
100
500
101
400
样例输出
500
提示
若约翰将前两天作为一个月,第三、四两天作为一个月,最后三天每天作为一个月,则最大月度开销为500。其他任何分配方案都会比这个值更大。
注意,二分的题目debug是比较困难的,所以在写程序的时候一定要仔细
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int arr[N];
int n, m;
bool check(int mid) {
int res = 0, count = 0;
for (int i = 0; i < n; i++) {
if (res + arr[i] > mid) {
count++;
res = arr[i];
}
else
res += arr[i];
}
return count >= m;
}
int main()
{
scanf("%d %d", &n, &m);
int maxV = 0;
int sum = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
maxV = max(maxV, arr[i]);
sum += arr[i];
}
int left = maxV, right = sum;
while (right >= left) {
int mid = left + (right - left) / 2;
if (check(mid))
left = mid + 1;
else
right = mid - 1;
}
printf("%d\n", left);
}
总时间限制:
1000ms
内存限制:
65536kB
描述
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?
输入
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
输出
* Line 1: One integer: the largest minimum distance
样例输入
5 3 1 2 8 4 9
样例输出
3
提示
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.
来源
USACO 2005 February Gold
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int arr[N];
int n, m;
bool check(int mid) {
int temp = arr[0];
int count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] - temp>= mid) {
temp = arr[i];
count++;
}
}
return count >= m;
}
int main()
{
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
sort(arr, arr + n);
int left = 1, right = arr[n - 1] - arr[0];
while (right >= left) {
int mid = left + (right - left) / 2;
if (check(mid))
left = mid + 1;
else
right = mid - 1;
}
printf("%d\n", right);
}