Posted on

Description

Submission

class Solution {
public:
    int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) {
        vector<int> connected(n);

        for(auto& pair: pairs) {
            connected[pair[0]] = pair[1];
            connected[pair[1]] = pair[0];
        }

        vector<vector<int>> order(n, vector<int>(n, INT_MAX));
        for(int i = 0; i < preferences.size(); ++i) {
            for(int j = 0; j < preferences[0].size(); ++j) {
                order[i][preferences[i][j]] = j;
            }
        }

        int ret = 0;
        for(int x = 0; x < n; ++x) {
            int y = connected[x];
            int index = order[x][y];    // find the pivot

            for(int i = 0; i < index; ++i) {    
                int u = preferences[x][i];
                int v = connected[u];
                if(order[u][x] < order[u][v]) {
                    ++ret;
                    break;
                }
            }
        }

        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *