P1824 进击的奶牛(二分)
思路:把检验的函数说一下,就是检测的距离x时,是否存在c个隔断相离大于等于x,如果是则返回1,不是则返回0
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; const int maxn = 1e5 + 10; int a[maxn], n, c, minn=0x3f3f3f3f, ans, mid; bool check(int x){ int sum = 0, base = a[1]; for (int i = 2; i <= n; ++i){ if (a[i] - base >= x){ sum++, base = a[i]; } if (sum >= c)return 1; } if (sum + 1 < c)return 0; return 1; } void half(){ int l = minn, r = a[n] - a[1]; while (l <= r){ mid = (l + r) >> 1; if (check(mid)){ l = mid + 1; } else r = mid - 1; } ans = r; } int main(){ scanf("%d%d", &n, &c); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); sort(a + 1, a + n + 1); for (int i = 2; i <= n; ++i) minn = min(minn, a[i] - a[i - 1]); half(); //二分 cout << ans << endl; }