Problem Description
Farmer John has received a noise complaint from his neighbor, Farmer Bob, stating that his cows are making too much noise.
FJ's N cows (1 <= N <= 10,000) all graze at various locations on a long one-dimensional pasture. The cows are very chatty animals. Every pair of cows simultaneously carries on a conversation (so every cow is simultaneously MOOing at all of the N-1 other cows). When cow i MOOs at cow j, the volume of this MOO must be equal to the distance between i and j, in order for j to be able to hear the MOO at all. Please help FJ compute the total volume of sound being generated by all N*(N-1) simultaneous MOOing sessions.
Input
* Line 1: N
* Lines 2..N+1: The location of each cow (in the range 0..1,000,000,000).
Output
There are five cows at locations 1, 5, 3, 2, and 4.
Sample Input
5 3
1
5
3
2
4Sample Output
3
题意:给出 n 个栏位以及其编号,现将 c 头牛放到栏位中,要求任意两头牛的栏位编号的最小差值最大。
思路:
一开始题的每个字都认识就是不知道要求什么,样例也看不明白,看了题解才稍微有些思路。
样例排序后,栏位编号是 1 2 4 8 9,那么 1 放一头牛,4 放一头牛,它们的差值为 3,最后一头牛放在 8 或 9 位置均可,和 4 的差值分别为 4、5,与 1 的差值分别为 7、8,均不比 3 小,所以最大的最小值为 3
现将栏位排序,则最大距离不会超过两端的两头牛之间的差值,最小值为0,可以通过二分枚举最小值来求。
假设当前的最小值为 x,如果最小差值为 x 时就可以放下 c 头牛,那么就让 x 变大再进行判断,如果放不下,说明当前 x 值太大,那么就让 x 变小再进行判断,直到求出一个最大的 x 值。
Source Program
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<vector>
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define N 100001
#define MOD 123
#define E 1e-6
using namespace std;
int n,c;
int stall[N];
bool judge(int x)
{
int temp=stall[0];
int cnt=1;
for(int i=1;i<n;i++)
{
if(stall[i]-temp>=x)
{
cnt++;
temp=stall[i];
if(cnt>=c)
return true;
}
}
return false;
}
int main()
{
scanf("%d%d",&n,&c);
for(int i=0;i<n;i++)
scanf("%d",&stall[i]);
sort(stall,stall+n);
int left=0,right=stall[n-1]-stall[0];
while(left<=right){
int mid=(left+right)/2;
if(judge(mid))
left=mid+1;
else
right=mid-1;
}
printf("%d\n",right);
return 0;
}