fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. inline int power(int a, int b) {
  6. int x = 1;
  7. while (b) {
  8. if (b & 1) x *= a;
  9. a *= a;
  10. b >>= 1;
  11. }
  12. return x;
  13. }
  14.  
  15.  
  16. const int M = 1000000007;
  17. const int N = 3e5+9;
  18. const int INF = 2e9+1;
  19. const int LINF = 2000000000000000001;
  20.  
  21. //_ ***************************** START Below *******************************
  22.  
  23.  
  24.  
  25. vector<int> a;
  26.  
  27.  
  28. int consistency1(int n, int k) {
  29.  
  30. int s= 0, e = n-1;
  31. int ans = 0;
  32.  
  33. //* keep in mind s<e (Not s<=e )
  34. while(s<e){
  35. int sum = a[s] + a[e];
  36. if(sum > k){
  37. ans += (e-s);
  38. e--;
  39. }
  40. else{
  41. s++;
  42. }
  43. }
  44.  
  45. return ans;
  46.  
  47. }
  48.  
  49.  
  50. //* Template 2
  51.  
  52. //* Think it as Reverse sliding window ,
  53. //* Expand Valid window =>
  54. //* sum > k
  55. //* e is decreasing (instead of increasing )
  56.  
  57. //* Shrink Invalid window => sum <= k
  58.  
  59. int consistency2(int n, int k) {
  60.  
  61. int s= 0, e = n-1;
  62. int ans = 0;
  63.  
  64.  
  65. while(e>=0){
  66. int sum = a[s] + a[e];
  67.  
  68. //* Invalid window : Shrink (cache invalidation style)
  69. while(s<e && a[s]+a[e] <= k) s++;
  70. if(s==e) break;
  71.  
  72. //* Valid window : Expand (e-- here)
  73. ans += (e-s);
  74. e--;
  75. }
  76.  
  77. return ans;
  78.  
  79. }
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92. int practice(int n, int k) {
  93. int ans = 0;
  94.  
  95. int s = 0, e = n-1;
  96. while(e>s){
  97. while(s<e && a[s]+a[e] <= k) s++;
  98. ans += e-s;
  99. e--;
  100. }
  101.  
  102. return ans;
  103.  
  104. }
  105.  
  106.  
  107.  
  108. void solve() {
  109.  
  110. int n, k;
  111. cin >> n >> k;
  112.  
  113. a.resize(n);
  114. for(int i=0; i<n; i++) cin >> a[i];
  115.  
  116. // cout << consistency1(n, k) << " " << consistency2(n, k) << endl;
  117.  
  118. cout << consistency1(n, k) << " -> " << practice(n, k) << endl;
  119. }
  120.  
  121.  
  122.  
  123.  
  124.  
  125. int32_t main() {
  126. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  127.  
  128. int t = 1;
  129. // cin >> t;
  130. while (t--) {
  131. solve();
  132. }
  133.  
  134. return 0;
  135. }
Success #stdin #stdout 0s 5316KB
stdin
5 8
1 2 7 9 10 
stdout
8 -> 8