1733. 需要教语言的最少人数

#哈希表 #贪心算法

https://leetcode.cn/problems/minimum-number-of-people-to-teach?envType=daily-question&envId=2025-09-10

题目:在一个由 m 个用户组成的社交网络里,我们获取到一些用户之间的好友关系。两个用户之间可以相互沟通的条件是他们都掌握同一门语言。

给你一个整数 n ,数组 languages 和数组 friendships ,它们的含义如下:

  • 总共有 n 种语言,编号从 1n
  • languages[i] 是第 i 位用户掌握的语言集合。
  • friendships[i] = [u​​​​​​i​​​, v​​​​​​i] 表示 u​​​​ivi 为好友关系。

你可以选择 一门 语言并教会一些用户,使得所有好友之间都可以相互沟通。请返回你 最少 需要教会多少名用户。

请注意,好友关系没有传递性,也就是说如果 xy 是好友,且 yz 是好友, xz 不一定是好友。


可以注意到,对于已经可以沟通的好友,我们不需要考虑,故而首先应当确定无法进行沟通的用户对。

cpp 复制代码
unordered_set<int>cncon;
for(auto friendship:friendships){
    unordered_set<int>st;
    bool conm=false;
    for(auto lan:languages[friendship[0]-1]){
        st.insert(lan);
    }
    for(auto lan:languages[friendship[1]-1]){
        if(st.find(lan)!=st.end()){
            conm=true;
            break;
        }
    }
    if(conm=false){
        cncon.insert([friendship[0]-1]);
        cncon.insert([friendship[1]-1]);
    }
    
}

找到所有无法沟通的用户之后,只需要再确定出掌握人数最多的语言即可。无法沟通的用户总人数减去掌握人数最多的语言人数,即为所求答案。

全部代码:

cpp 复制代码
class Solution {
public:
    int minimumTeachings(int n, vector<vector<int>>& languages, vector<vector<int>>& friendships) {
        //存储不能相互沟通的好友
        unordered_set<int>cncon;
        for(auto friendship:friendships){
            unordered_map<int,int>mp;
            bool conm=false;
            for(int lan:languages[friendship[0]-1]){
                mp[lan]=1;
            }
            for(int lan:languages[friendship[1]-1]){
                if(mp[lan]==1){
                    conm=true;
                    break;
                }
            }
            if(!conm){
                cncon.insert(friendship[0]-1);
                cncon.insert(friendship[1]-1);
            }
        }
        int max_cnt=0;
        //统计无法沟通的人中,每一种语言掌握的人数
        vector<int>cnt(n+1,0);
        for(auto friendship:cncon){
            for(int lan:languages[friendship]){
                cnt[lan]++;
                max_cnt=max(max_cnt,cnt[lan]);
            }
        }
        return cncon.size()-max_cnt;

        
    }
};
相关推荐
小O的算法实验室20 小时前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
郭涤生21 小时前
STL vector 扩容机制与自定义内存分配器设计分析
c++·算法
༾冬瓜大侠༿21 小时前
vector
c语言·开发语言·数据结构·c++·算法
Ricky111zzz1 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
汀、人工智能1 天前
[特殊字符] 第58课:两个正序数组的中位数
数据结构·算法·数据库架构··数据流·两个正序数组的中位数
liu****1 天前
第16届省赛蓝桥杯大赛C/C++大学B组(京津冀)
开发语言·数据结构·c++·算法·蓝桥杯
汀、人工智能1 天前
[特殊字符] 第79课:分割等和子集
数据结构·算法·数据库架构·位运算·哈希表·分割等和子集
汀、人工智能1 天前
[特殊字符] 第74课:完全平方数
数据结构·算法·数据库架构·图论·bfs·完全平方数
CoderCodingNo1 天前
【GESP】C++四、五级练习题 luogu-P1177 【模板】排序
数据结构·c++·算法
Proxy_ZZ01 天前
从零实现LDPC比特翻转译码器:C语言实战与底层逻辑解析
c语言·算法