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 t from the input.
  • We then iterate t times, each time reading the length of the array n, the array a, the number of queries q, and the queries themselves.
  • For each query, we create a frequency map freq to keep track of the occurrences of each element in the array.
  • We initialize a variable count to keep track of the number of pairs satisfying the conditions.
  • We iterate over each element ai in the array and calculate the corresponding aj such that ai + aj = x.
  • If aj exists in the frequency map, we add the frequency of aj to the count.
  • We then update the frequency of ai in 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

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

原文地址: https://www.cveoy.top/t/topic/iwTa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录