首页 技术 正文
技术 2022年11月14日
0 收藏 551 点赞 4,356 浏览 1038 个字

婴儿名字

题目[Interview-1707]:典型并查集题目。

解题思路

首先对 names 这种傻 X 字符串结构进行预处理,转换为一个 mapkey 是名字,val 是名字出现的次数。

然后是把 synonyms 转换为并查集结构,需要注意的是:总是把字典序较小的名字作为连通分量的根。

最后以连通分量的根作为代表,计算每个连通分量的总权重(即每个名字的次数之和)。

代码实现

class Solution
{
public:
unordered_map<string, string> root;
vector<string> trulyMostPopular(vector<string> &names, vector<string> &synonyms)
{
vector<string> ans;
unordered_map<string, int> table;
for (auto &s : names)
{
int idx = s.find('(');
string n = s.substr(0, idx);
int val = stoi(s.substr(idx + 1, s.length() - 2 - idx));
table[n] = val;
}
// build the disjoint-union set
for (auto &str : synonyms)
{
int idx = str.find(',');
string n1 = str.substr(1, idx - 1);
string n2 = str.substr(idx + 1, str.length() - 2 - idx);
merge(n1, n2);
}
// calculate the frequency of root nodes
unordered_map<string, int> mapAns;
for (auto &p : table)
mapAns[find(p.first)] += p.second; for (auto &p : mapAns)
{
string s = p.first + "(" + to_string(p.second) + ")";
ans.emplace_back(s);
} return ans;
}
string find(string x)
{
return root.count(x) == 0 ? (x) : (root[x] = find(root[x]));
}
void merge(string x, string y)
{
x = find(x), y = find(y);
if (x < y)
root[y] = x;
else if (x > y)
root[x] = y;
// do nothing if x == y
}
};

冗余连接 Ⅱ

题目[685]:

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,493
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297