fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Find total number of pairs (i,j), i < j,
  5. // such that abs(nums[i] + nums[j]) = target
  6.  
  7. int main()
  8. {
  9. int n;
  10. int target;
  11. int res = 0;
  12.  
  13. cin >> n >> target;
  14.  
  15. vector<int> ar;
  16.  
  17. for (int i = 0; i < n; i++)
  18. {
  19. int y;
  20. cin >> y;
  21. ar.push_back(y);
  22. }
  23.  
  24. unordered_map<int, int> mp;
  25.  
  26. for (int j = 0; j < n; j++)
  27. {
  28. int def_1 = target-ar[j];
  29. int def_2 = -target-ar[j];
  30.  
  31. if (mp.count(def_1))
  32. res += mp[def_1];
  33.  
  34. if (mp.count(def_2))
  35. res += mp[def_2];
  36.  
  37. mp[ar[j]]++;
  38. }
  39.  
  40. cout << res << endl;
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0.01s 5308KB
stdin
6
2 
2 2 3 3 5 5
stdout
0