Problem Description
Problem Analysis
Maximizing the minimum value
This is also solved with binary search
Continuously check mid
to see whether it satisfies the condition
When checking whether it is valid
you can place the first cow in the first stall
then select stalls separated by more than mid
If the number of selectable stalls is greater than C
it means mid is feasible
so continue searching for a larger distance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| #include<stdio.h>
#include<algorithm>
using namespace std;
int a[100200];
int n,c;
bool judge(int m) {
int last=0,cnt=1;
for(int i=1; i<n; i++) {
if(a[i]-a[last]>=m) {
last=i;
cnt++;
}
}
if(cnt>=c)
return true;
else
return false;
}
int main() {
while(scanf("%d %d",&n,&c)!=EOF) {
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
int r=a[n-1]-a[0],l=1;
int mid,res;
while(r>=l) {
mid=(r+l)/2;
if(judge(mid)) {
res=mid;
l=mid+1;
} else
r=mid-1;
}
printf("%d\n",res);
}
return 0;
}
|
Problem link: POJ 2456 Aggressive cows