fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8. int n;
  9. if (!(cin >> n)) return 0;
  10. vector<int> arr(n);
  11. for (int i = 0; i < n; i++) {
  12. cin >> arr[i];
  13. }
  14.  
  15. long long int target;
  16. cin >> target;
  17.  
  18. // Use long long to avoid integer overflow during multiplications
  19. long long int c1 = 0;
  20. long long int c2 = 0;
  21. long long int c3 = 0;
  22. long long int c4 = 0;
  23.  
  24. // target must be non-negative and even
  25. if (target >= 0 && target % 2 == 0) {
  26. long long int k = target / 2;
  27. for (int i = 0; i < n; i++) {
  28. if (arr[i] == k) {
  29. c1++;
  30. } else if (arr[i] == -k) {
  31. c2++;
  32. } else if (arr[i] >= 0 && abs(arr[i]) < k) {
  33. c3++;
  34. } else if (arr[i] < 0 && abs(arr[i]) < k) {
  35. c4++;
  36. }
  37. }
  38. }
  39.  
  40. long long int ans = 0;
  41.  
  42. // Case A: Pairs where both elements have magnitude K
  43. ans = ans + c1 * (c1 - 1) / 2; // (+K, +K)
  44. ans = ans + c2 * (c2 - 1) / 2; // (-K, -K)
  45. ans = ans + c1 * c2; // (+K, -K)
  46.  
  47. // Case B: Pairs where one element is +K and the other has smaller magnitude
  48. ans = ans + c1 * c4;
  49. ans = ans + c1 * c3;
  50.  
  51. // Case C: Pairs where one element is -K and the other has smaller magnitude
  52. ans = ans + c2 * c3;
  53. ans = ans + c2 * c4;
  54.  
  55. cout << ans << endl;
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 5320KB
stdin
4
1 3 2 0
2
stdout
1