fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. #define print(a) for(auto x : a) cout << x << " "; cout << endl
  6. inline int power(int a, int b) {
  7. int x = 1;
  8. while (b) {
  9. if (b & 1) x *= a;
  10. a *= a;
  11. b >>= 1;
  12. }
  13. return x;
  14. }
  15.  
  16.  
  17. const int M = 1000000007;
  18. const int N = 3e5+9;
  19. const int INF = 2e9+1;
  20. const int LINF = 2000000000000000001;
  21.  
  22. //_ ***************************** START Below *******************************
  23.  
  24. vector<int> a;
  25.  
  26. bool isPossible(int n, int k, vector<int>& a, int mid){
  27. int cows = 1;
  28. for(int i=0; i<n; ){
  29. int j = i+1;
  30. while(j<n && a[j] - a[i] < mid) j++;
  31. if(j==n) break;
  32. cows++;
  33. i = j;
  34. }
  35. return cows>=k;
  36. }
  37.  
  38. int consistency1(int n, int k){
  39. vector<int> b(a);
  40. sort(begin(b), end(b));
  41.  
  42. int s = 0, e = INF;
  43. int ans = 0;
  44. while(s<=e){
  45. int mid = s + (e-s)/2;
  46. if(isPossible(n, k, b, mid)){
  47. ans = max(ans, mid);
  48. s = mid+1;
  49. }
  50. else{
  51. e = mid-1;
  52. }
  53.  
  54. }
  55.  
  56. return ans;
  57.  
  58. }
  59.  
  60.  
  61.  
  62. int consistency2(int n, int k){
  63.  
  64. vector<int> b(a);
  65.  
  66. sort(begin(b), end(b));
  67.  
  68. int s = 0, e = INF;
  69.  
  70. while(s<e){
  71. int mid = s + (e-s+1)/2;
  72. if(isPossible(n, k, b, mid)){
  73. s = mid;
  74. }
  75. else e = mid-1;
  76. }
  77.  
  78. return e;
  79.  
  80. }
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94. bool isPoss(int n, int k, int mid){
  95.  
  96. int ct = 1;
  97.  
  98. for(int i=0; i<n; ){
  99. int j = i+1;
  100. while(j<n && a[j] - a[i] < mid) j++;
  101. if(j==n) break;
  102.  
  103. ct++;
  104. i = j;
  105. }
  106.  
  107. return ct >= k;
  108. }
  109.  
  110. int practice(int n, int k){
  111. sort(begin(a), end(a));
  112.  
  113. int s = 0, e = INF;
  114. while(s<e){
  115. int mid = s + (e-s+1)/2;
  116. if(isPoss(n, k, mid)){
  117. s = mid;
  118. }
  119. else e = mid-1;
  120. }
  121.  
  122.  
  123. return e;
  124.  
  125. }
  126.  
  127.  
  128.  
  129.  
  130.  
  131. void solve() {
  132.  
  133. int n, k;
  134. cin>>n >> k;
  135. a.resize(n);
  136.  
  137. for(int i=0; i<n; i++) cin >> a[i];
  138. // cout << consistency1(n, k) << " " << consistency2(n,k) << endl;
  139.  
  140. cout << consistency1(n, k) << " -> " << practice(n, k) << endl;
  141.  
  142. }
  143.  
  144.  
  145.  
  146.  
  147.  
  148. int32_t main() {
  149. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  150.  
  151. int t = 1;
  152. // cin >> t;
  153. while (t--) {
  154. solve();
  155. }
  156.  
  157. return 0;
  158. }
Success #stdin #stdout 0s 5320KB
stdin
5 3
1 2 8 4 9
stdout
3 -> 3