zoukankan      html  css  js  c++  java
  • b_lc_统计不开心的朋友(预处理+模拟)

    给你一份 n 位朋友的亲近程度列表,其中 n 总是 偶数 。
    对每位朋友 i,preferences[i] 包含一份 按亲近程度从高到低排列 的朋友列表。换句话说,排在列表前面的朋友与 i 的亲近程度比排在列表后面的朋友更高。每个列表中的朋友均以 0 到 n-1 之间的整数表示。
    所有的朋友被分成几对,配对情况以列表 pairs 给出,其中 pairs[i] = [xi, yi] 表示 xi 与 yi 配对,且 yi 与 xi 配对。
    但是,这样的配对情况可能会是其中部分朋友感到不开心。在 x 与 y 配对且 u 与 v 配对的情况下,如果同时满足下述两个条件,x 就会不开心:

    • x 与 u 的亲近程度胜过 x 与 y,且
    • u 与 x 的亲近程度胜过 u 与 v

    返回 不开心的朋友的数目 。

    输入:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
    输出:2
    解释:
    朋友 1 不开心,因为:
    - 1 与 0 配对,但 1 与 3 的亲近程度比 1 与 0 高,且
    - 3 与 1 的亲近程度比 3 与 2 高。
    朋友 3 不开心,因为:
    - 3 与 2 配对,但 3 与 1 的亲近程度比 3 与 2 高,且
    - 1 与 3 的亲近程度比 1 与 0 高。
    朋友 0 和 2 都是开心的。
    
    提示:2 <= n <= 500
    

    这个不开心不是 x 与 u 的亲近程度胜过 x 与 y,就是 qinmi_xu>qinmi_xy 吗,我开始就是按照这个写的,预处理也考虑了,但是还是理解错了,改了15分钟还是没法先问题,直到将 > 换成 < 后(因为rk[u][v]越小,亲密度越大鸭)

    class Solution {
    public:
        unordered_map<int, unordered_map<int, int>> rk;
        bool has_unhappy(int x, int y, int u, int v) {
            return rk[x][u]<rk[x][y] && rk[u][x]<rk[u][v];
        }
        int unhappyFriends(int n, vector<vector<int>>& g, vector<vector<int>>& ps) {
            for (int i=0; i<n; i++)
            for (int j=0; j<g[i].size(); j++)
                rk[i][g[i][j]]=j;
            
            int ans=0, m=ps.size(), unhappy[n]; memset(unhappy, false, sizeof unhappy);
            for (int i=0; i<m; i++)
            for (int j=0; j<m; j++) if (i!=j) {
                int x=ps[i][0], y=ps[i][1], u=ps[j][0], v=ps[j][1];
                if (has_unhappy(x,y,u,v) || has_unhappy(x,y,v,u)) unhappy[x]=1;
                if (has_unhappy(y,x,u,v) || has_unhappy(y,x,v,u)) unhappy[y]=1;
            }
            for (int i=0; i<n; i++) if (unhappy[i])
                ans++;
            return ans;
        }
    };
    
  • 相关阅读:
    常用知识点集合
    LeetCode 66 Plus One
    LeetCode 88 Merge Sorted Array
    LeetCode 27 Remove Element
    LeetCode 26 Remove Duplicates from Sorted Array
    LeetCode 448 Find All Numbers Disappeared in an Array
    LeetCode 219 Contains Duplicate II
    LeetCode 118 Pascal's Triangle
    LeetCode 119 Pascal's Triangle II
    LeetCode 1 Two Sum
  • 原文地址:https://www.cnblogs.com/wdt1/p/13660848.html
Copyright © 2011-2022 走看看