You have an array a of length nYour task is to answer q queries given xy find the number of pairs i and j 1≤ij≤n that both ai+aj=x and ai⋅aj=yThat is for the array 132 and asking for x=3y=2 the answer
Here is a possible implementation in C++:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int q;
cin >> q;
while (q--) {
int x, y;
cin >> x >> y;
unordered_map<int, int> freq;
int count = 0;
for (int i = 0; i < n; i++) {
int ai = a[i];
int aj = x - ai;
if (freq.count(aj)) {
count += freq[aj];
}
freq[ai]++;
}
cout << count << " ";
}
cout << endl;
}
return 0;
}
Explanation:
- We start by reading the number of test cases
tfrom the input. - We then iterate
ttimes, each time reading the length of the arrayn, the arraya, the number of queriesq, and the queries themselves. - For each query, we create a frequency map
freqto keep track of the occurrences of each element in the array. - We initialize a variable
countto keep track of the number of pairs satisfying the conditions. - We iterate over each element
aiin the array and calculate the correspondingajsuch thatai + aj = x. - If
ajexists in the frequency map, we add the frequency ofajto the count. - We then update the frequency of
aiin the map. - Finally, we output the count for each query and move to the next test case.
This solution has a time complexity of O(t * (n + q)), where t is the number of test cases, n is the length of the array, and q is the number of queries
原文地址: https://www.cveoy.top/t/topic/iwTa 著作权归作者所有。请勿转载和采集!