Untitled

 avatar
domovonok
c_cpp
a year ago
2.0 kB
5
Indexable
#include "bits/stdc++.h"
using namespace std;

#ifdef LOCAL
#include "debug.h"
#else
#define debug(x...)
#endif

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

void solve() {
    int n, m;
    cin >> n >> m;
    unordered_map<int, int, custom_hash> cp;
    vector<int> pos[n];
    for (int i = 0; i < n; i++) {
        int a;
        cin >> a;
        if (cp.find(a) == cp.end()) {
            cp[a] = (int)cp.size();
        }
        pos[cp[a]].push_back(i);
    }
    vector<unordered_map<int, long long, custom_hash>> memo(n);
    while (m--) {
        int x, y;
        cin >> x >> y;
        x = cp[x];
        y = cp[y];
        if (memo[x].count(y)) {
            cout << memo[x][y] << '\n';
            continue;
        }
        long long res = 0;
        if (pos[x].size() <= pos[y].size()) {
            for (int i = 0; i < (int)pos[x].size(); i++) {
                int cnty = pos[y].size() - (upper_bound(pos[y].begin(), pos[y].end(), pos[x][i]) - pos[y].begin());
                res = max(res, 1LL * (i + 1) * cnty);
            }
        } else {
            for (int i = 0; i < (int)pos[y].size(); i++) {
                int cntx = upper_bound(pos[x].begin(), pos[x].end(), pos[y][i]) - pos[x].begin();
                if (x == y) cntx--;
                res = max(res, 1LL * ((int)pos[y].size() - i) * cntx);
            }
        }
        memo[x][y] = res;
        cout << res << '\n';
    }

}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int tests = 1;
    // cin >> tests;
    while (tests--) {
        solve();
    }
    return 0;
}