首页 > 代码库 > [luoguP1316] 丢瓶盖(二分答案)

[luoguP1316] 丢瓶盖(二分答案)

传送门

 

二分答案再判断即可

 

——代码

技术分享
 1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #define max(x, y) ((x) > (y) ? (x) : (y)) 5 #define N 1000001 6  7 int n, m, ans, maxn; 8 int a[N]; 9 10 inline int read()11 {12     int x = 0, f = 1;13     char ch = getchar();14     for(; !isdigit(ch); ch = getchar()) if(ch == -) f = -1;15     for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - 0;16     return x * f;17 }18 19 inline bool check(int x)20 {21     int i, now = 1, sum = 1;22     for(i = 1; i <= n; i++)23         if(a[i] - a[now] >= x)24         {25             sum++;26             now = i;27         }28     return sum >= m;29 }30 31 int main()32 {33     int i, j, x, y, mid;34     n = read();35     m = read();36     for(i = 1; i <= n; i++) a[i] = read(), maxn = max(a[i], maxn);37     std::sort(a + 1, a + n + 1);38     x = 1, y = maxn;39     while(x <= y)40     {41         mid = (x + y) >> 1;42         if(check(mid)) ans = mid, x = mid + 1;43         else y = mid - 1;44     }45     printf("%d\n", ans);46     return 0;47 }
View Code

 

[luoguP1316] 丢瓶盖(二分答案)