fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. // Function to check if we can place m cameras with max distance S
  8. bool canPlaceCameras(const vector<long long>& houses, int n, int m, long long S) {
  9. int camerasUsed = 1; // Place the first camera at houses[0]
  10. long long lastCameraPos = houses[0];
  11.  
  12. for (int i = 1; i < n; i++) {
  13. if (houses[i] - lastCameraPos > S) {
  14. camerasUsed++;
  15. lastCameraPos = houses[i]; // Place a new camera
  16. if (camerasUsed > m) return false;
  17. }
  18. }
  19. return true;
  20. }
  21.  
  22. int main() {
  23. // Read input
  24. int n, m;
  25. cin >> n >> m;
  26. vector<long long> houses(n);
  27. for (int i = 0; i < n; i++) {
  28. cin >> houses[i];
  29. }
  30.  
  31. // Binary search for minimum S
  32. long long left = 0, right = houses[n - 1] - houses[0], answer = right;
  33. while (left <= right) {
  34. long long mid = (left + right) / 2;
  35. cout << mid << ' ';
  36. if (canPlaceCameras(houses, n, m, mid)) {
  37. answer = mid; // Try smaller S
  38. right = mid - 1;
  39. } else {
  40. left = mid + 1;
  41. }
  42. }
  43.  
  44. cout << answer << endl;
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0.01s 5268KB
stdin
6 3
4 6 12 39 40 100
stdout
48 23 11 5 8 6 7 8