二分最大距离,判断条件是每次要删除的点和要求的是否大小相等
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5 6 const int MAXN = 50010; 7 int d[MAXN]; 8 int x; 9 int n, m; 10 11 int search(int l, int r){ 12 int del; //记录消灭的数量 13 int mid; 14 while (r - l>1){ 15 mid = (l + r) / 2; //进行二分 16 del = 0; 17 int i = 0; 18 for (int j = i + 1; j<n + 2; j++){ 19 if (d[j] - d[i]<mid) //小于mid值就消灭 20 del++; 21 else //否则将i值增加,继续查找 22 i = j; 23 } 24 if (del <= m)//当相等,则说明满足条件,小于则说明值偏小 25 l = mid; 26 else //大于则折半缩小mid的值 27 r = mid; 28 } 29 return l; 30 } 31 32 int main(){ 33 cin >> x >> n >> m; 34 int ans; 35 int l = x; 36 d[0] = 0; d[n + 1] = x; 37 for (int i = 1; i <= n; i++) 38 cin >> d[i]; 39 sort(d, d + n + 2); //对距离进行排序 40 ans = search(0, x); 41 cout << ans << endl; 42 return 0; 43 }
时间: 2024-10-12 08:27:46