Official

B - Which is ahead? Editorial by en_translator


Construct an array \(Q\) such that person \(i\) is \(Q_i\)-th person from the front.

Then, the query can be processed by simply comparing \(Q_{A_i}\) and \(Q_{B_i}\).

To construct \(Q\), let \(Q_{P_i}=i\) for each \(i\).

The following is sample code in C++ language.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> P(n);
    for(int i = 0; i < n; i++) cin >> P[i];
    vector<int> Q(n + 1);
    for(int i = 0; i < n; i++) Q[P[i]] = i;
    int q;
    cin >> q;
    for(int i = 0; i < q; i++) {
        int a, b;
        cin >> a >> b;
        if(Q[a] < Q[b])
            cout << a << endl;
        else
            cout << b << endl;
    }
}

posted:
last update: