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.  
  7.  
  8. const int M = 1000000007;
  9. const int N = 3e5+9;
  10. const int INF = 2e9+1;
  11. const int LINF = 2000000000000000001;
  12.  
  13. inline int power(int a, int b, int mod=M) {
  14. int x = 1;
  15. a %= mod;
  16. while (b) {
  17. if (b & 1) x = (x * a) % mod;
  18. a = (a * a) % mod;
  19. b >>= 1;
  20. }
  21. return x;
  22. }
  23.  
  24.  
  25. //_ ***************************** START Below *******************************
  26.  
  27. // 7 20
  28. // 1 2 2 3 4 4 6
  29.  
  30.  
  31. vector<int> a;
  32.  
  33. //* no. of pairs with dist <= x
  34.  
  35. //* x = 2
  36.  
  37. // ( 2 4 ) 5 5 6 7
  38. // 2 ( 4 5 ) 5 6 7
  39. // 2 ( 4 5 5 ) 6 7
  40. // 2 ( 4 5 5 6) 7
  41. // 2 4 ( 5 5 6 7 )
  42.  
  43.  
  44. int count(int n, int x){
  45. int ct = 0;
  46. int s = 0, e = 0;
  47.  
  48. while(e<n && s<n-1){
  49. if(s==e) e++;
  50. if(a[e]-a[s] <= x){
  51. e++;
  52. ct += e-s;
  53. }
  54. else{
  55. s++;
  56. }
  57.  
  58. }
  59.  
  60. return ct;
  61. }
  62.  
  63. int consistency(int n, int k){
  64.  
  65. sort(begin(a), end(a));
  66.  
  67. int s = 0, e = a[n-1]-a[0];
  68.  
  69. while(s<e){
  70. int mid = s + (e-s)/2;
  71. if(count(n, mid) >= k){
  72. e = mid;
  73. }
  74. else s = mid+1;
  75. }
  76.  
  77. return e;
  78.  
  79. }
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95. int practice(int n, int k){
  96.  
  97.  
  98. return 0;
  99. }
  100.  
  101.  
  102.  
  103.  
  104.  
  105. void solve() {
  106.  
  107. int n, k;
  108. cin>> n >> k;
  109.  
  110. a.resize(n);
  111. for(int i=0; i<n; i++) cin >> a[i];
  112.  
  113. cout << consistency(n, k) << endl;
  114.  
  115.  
  116. }
  117.  
  118.  
  119.  
  120.  
  121.  
  122. int32_t main() {
  123. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  124.  
  125. int t = 1;
  126. // cin >> t;
  127. while (t--) {
  128. solve();
  129. }
  130.  
  131. return 0;
  132. }
Success #stdin #stdout 0.01s 5320KB
stdin
7 20
1 2 2 3 4 4 5
stdout
2