fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. int n,target;
  7. cin>>n>>target;
  8. int arr[n];
  9. for(int i = 0; i < n; i++){
  10. cin>>arr[i];
  11. }
  12. unordered_map<int,int> ump;
  13.  
  14. int cnt = 0;
  15.  
  16. for(int j = 0; j < n; j++){
  17. int r1 = arr[j] + target;
  18. int r2 = arr[j] - target;
  19.  
  20. //Here ump[r] tells us the frequency of targer-arr[j] in the left side of j
  21.  
  22. if (target == 0) {
  23. // r1 == r2, so count only once
  24. cnt += ump[r1];
  25. }
  26. else {
  27. cnt += ump[r1];
  28. cnt += ump[r2];
  29. }
  30.  
  31. ump[arr[j]]++;
  32. }
  33. cout<<cnt<<endl;
  34. return 0;
  35. }
Success #stdin #stdout 0s 5312KB
stdin
6
2
7
2
2
3
3
5
5
stdout
3