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.  
  29. int consistency1(int n, int k) {
  30.  
  31. int ans = 0;
  32. int s = 0, e = n-1;
  33.  
  34. //* keep in mind s<e (Not s<=e )
  35. while(s<e){
  36. if(a[s] + a[e] > k){
  37. e--;
  38. }
  39. else{
  40. ans += (e-s);
  41. s++;
  42. }
  43. }
  44. return ans;
  45.  
  46. }
  47.  
  48.  
  49. //* Template 2 :
  50. //* Invalid window => sum > k
  51. //* Valid window => sum <= k
  52.  
  53. int consistency2(int n, int k) {
  54.  
  55.  
  56. int ans = 0;
  57. int s = 0, e = n-1;
  58.  
  59. while(s<e){
  60.  
  61. while(s<e && a[s]+a[e] > k) e--;
  62. if(s==e) break;
  63.  
  64. ans += (e-s);
  65. s++;
  66. }
  67. return ans;
  68.  
  69. }
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79. int practice(int n, int k) {
  80.  
  81. int ans = 0;
  82. int s = 0, e = n-1;
  83. while(s<e){
  84.  
  85. while(e>s && a[s] + a[e] > k) e--;
  86. if(e==s) break;
  87.  
  88. ans += e-s;
  89. s++;
  90. }
  91.  
  92.  
  93. return ans;
  94. }
  95.  
  96.  
  97. void solve() {
  98.  
  99. int n, k;
  100. cin >> n >> k;
  101.  
  102. a.resize(n);
  103.  
  104. for(int i=0; i<n; i++) cin >> a[i];
  105.  
  106. // cout << consistency1(n, k) << " " << consistency2(n, k) << endl;
  107.  
  108. cout << consistency1(n, k) << " -> " << practice(n, k) << endl;
  109.  
  110. }
  111.  
  112.  
  113.  
  114.  
  115.  
  116. int32_t main() {
  117. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  118.  
  119. int t = 1;
  120. // cin >> t;
  121. while (t--) {
  122. solve();
  123. }
  124.  
  125. return 0;
  126. }
Success #stdin #stdout 0.01s 5308KB
stdin
5 16
1 5 10 15 20
stdout
4 -> 4