Problem. men and women each rank the other side. Find a matching with no blocking pair (a man and a woman who both prefer each other to their partners).

Gale–Shapley: free men propose in order of preference; a woman keeps the best proposal so far. Always terminates in with a stable matching that is the best possible for every man (and the worst for every woman) among all stable matchings.

vector<int> galeShapley(const vector<vector<int>>& pm, const vector<vector<int>>& pw) {   // men propose; returns wife of each man
    int n = sz(pm); vector<vector<int>> rank(n, vector<int>(n));
    for (int w = 0; w < n; w++) for (int i = 0; i < n; i++) rank[w][pw[w][i]] = i;
    vector<int> next(n, 0), husband(n, -1), wife(n, -1); queue<int> freeMen;
    for (int m = 0; m < n; m++) freeMen.push(m);
    while (sz(freeMen)) {
        int m = freeMen.front(); freeMen.pop(); int w = pm[m][next[m]++];
        if (husband[w] < 0) husband[w] = m, wife[m] = w;
        else if (rank[w][m] < rank[w][husband[w]]) { wife[husband[w]] = -1; freeMen.push(husband[w]); husband[w] = m; wife[m] = w; }
        else freeMen.push(m);
    }
    return wife;
}