fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. int qs11(vector<int>arr,int k1,int k2){
  5. int n=arr.size();
  6. vector<int>suffix(n,0);
  7. vector<int>s(n,0);
  8.  
  9. for(int k=0;k<n;k++){
  10. int res=-1;
  11. int low=k+1;
  12. int high=n-1;
  13. int req=k2-arr[k];
  14. while(low<=high){
  15. int mid=(low+high)/2;
  16. if(arr[mid]>req){
  17. res=mid;
  18. high=mid-1;
  19. }
  20. else {
  21. low=mid+1;
  22. }
  23. }
  24.  
  25. if(res!=-1){
  26. s[k]=n-res;
  27. }
  28. }
  29.  
  30. suffix[n-1]=s[n-1];
  31. for(int i=n-2;i>=0;i--){
  32. suffix[i]=s[i]+suffix[i+1];
  33. }
  34.  
  35. //Main logic of the code
  36. int count=0;
  37.  
  38. for(int i=1;i<n-2;i++){
  39. int c1=0;
  40. int low=0;
  41. int high=i-1;
  42. int req=k1-arr[i];
  43. int r=-1;
  44. while(low<=high){
  45. int mid=(low+high)/2;
  46. if(arr[mid]>req){
  47. r=mid;
  48. high=mid-1;
  49. }
  50. else{
  51. low=mid+1;
  52. }
  53. }
  54. if(r!=-1){
  55. c1=i-r;
  56. }
  57.  
  58. int c2=0;
  59. c2=suffix[i+1];
  60.  
  61. count+=c1*c2;
  62. }
  63.  
  64. return count;
  65. }
  66.  
  67. int main(){
  68. int n;
  69. cin>>n;
  70. vector<int>arr(n);
  71. for(int i=0;i<n;i++){
  72. cin>>arr[i];
  73. }
  74. int k1,k2;
  75. cin>>k1;
  76. cin>>k2;
  77.  
  78. int result=qs11(arr,k1,k2);
  79. cout<<"The number of quadruplets from the array which satisfies the given condition: "<<result<<endl;
  80. return 0;
  81.  
  82. }
Success #stdin #stdout 0s 5320KB
stdin
7
1 3 4 6 7 8 9
7
10
stdout
The number of quadruplets from the array which satisfies the given condition: 10