Question link: http://poj.org/problem? Id = 2456
Question Translation:
John, the farmer, built a house where n cows were willing to go. The barn was placed in a straight line and the No. I ox tongue was placed in Xi. However, his m-headed ox is not satisfied with the hut, so he often attacks each other. To prevent mutual harm, John decided to put every ox in a barn as far away as possible from other cows. That is, to maximize the distance between the nearest two cows.
Restrictions
2 <= n <= 100000
2 <= m <= N
0 <= xi <= 10 ^ 9
Idea: The template question in the <challenge Programming Competition> is a question of finding the maximum and minimum values. First, we will build a basic problem-solving framework. Binary + greedy. Use the binary method to enumerate the distance and determine whether the distance meets the requirements until the maximum value is found. How can we make a decision? We can sort them with greed.
Code:
# Include <iostream> # include <algorithm> # include <cstdio> using namespace STD; int n, m; int A [100001]; // judgment function Int J (int x) {int C, last; last = 1; for (INT I = 1; I <m; I ++) {c = last + 1; while (C <= N & A [c]-A [last] <X) {C ++;} If (C = n + 1) return false; last = C;} return true;} int main () {int R, L, mid; while (scanf ("% d", & N, & M )! = EOF) {for (INT I = 1; I <= N; I ++) {scanf ("% d", A + I );} // sort (A, A + n + 1); L = 0; r = 1000000000; // binary while (L + 1 <R) {mid = (R + l)/2; If (J (MID) = true) {L = mid;} else {r = mid ;}} printf ("% d \ n", L);} return 0 ;}
Poj 2456 aggressive cows