#include <iostream>
#include <unordered_map>
int countPairsWithSumX(int arr[], int n, int X) {
std::unordered_map<int, int> freqMap;
int pairCount = 0;
for (int i = 0; i < n; i++) {
int complement = X - arr[i];
if (freqMap.find(complement)!= freqMap.end()) {
pairCount += freqMap[complement];
}
freqMap[arr[i]]++;
}
return pairCount;
}
int main() {
int testCaseNum;
std::cin >> testCaseNum;
for (int testCase = 0; testCase < testCaseNum; testCase++) {
int n;
std::cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
int X;
std::cin >> X;
int result = countPairsWithSumX(arr, n, X);
std::cout << result << std::endl;
}
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
struct Pair {
using num_t = long;
using sum_t = long long;
num_t a;
num_t b;
bool matches(const sum_t k) const {
return (sum_t)a + (sum_t)b == k;
}
};
class Task {
public:
Task(const vector<Pair::num_t>& present) {
const size_t n = present.size();
const auto m = n - 1;
for (size_t i = 0; i < m; ++i) {
for (size_t j = i + 1; j < n; ++j) {
pairs.emplace_back(Pair{ present[i], present[j] });
}
}
}
size_t count(const Pair::sum_t k) const {
size_t quantity = 0;
for (const auto& item : pairs) {
if (item.matches(k)) {
++quantity;
}
}
return quantity;
}
private:
vector<Pair> pairs;
};
int main() {
size_t i = 0, t;
cin >> t;
vector<size_t> results(t);
while (i < t) {
size_t n;
cin >> n;
Pair::sum_t k;
cin >> k;
vector<Pair::num_t> present(n);
for (auto& number : present) cin >> number;
Task task(present);
results[i] = task.count(k);
++i;
}
for (auto result : results) {
cout << result << '\n';
}
}
Входные данные
3
3 1
0 1 0
2 -1
-2 1
4 3
1 2 3 -1
Результат работы
2
1
1