当前位置:网站首页>[英雄星球七月集训LeetCode解题日报] 第26日 并查集
[英雄星球七月集训LeetCode解题日报] 第26日 并查集
2022-07-26 19:59:00 【七水shuliang】
日报
- 今日并查集以为是水题结果wa了一次。
题目
一、 面试题 17.07. 婴儿名字
链接: 面试题 17.07. 婴儿名字
1. 题目描述

2. 思路分析
- 题面很清晰,其实就是并查集归出所有的祖宗节点(同族字典序最小的单词),然后每个数的频率都统计到祖宗头上。
- 我wa了一次在于union之前判断x,y的字典序,然后把x合并向y,这样是错误的,因为路径压缩后,x的祖宗和y的祖宗字典序不一定谁大谁小呢,因此要在union内部:x,y都路径压缩后比较祖宗的字典序,然后选择方向合并。
- 由于我的并查集模板是数组的,因此需要先对单词进行离散化,映射成数字下标进行并查集,比较麻烦。下边打算整理一个基于字典的模板。
- 实测不离散化更快。
- 基于字典的并查集要注意,findfather和union之前,把x,y都setdefault本身

3. 代码实现
原答案
class UnionFind:
def __init__(self,size):
self.fathers = list(range(size))
def find_father(self,x):
return self._zip_find_father(x)
def _zip_find_father(self,x):
fathers = self.fathers
if fathers[x] != x:
fathers[x] = self._zip_find_father(fathers[x])
return fathers[x]
def union(self,x,y):
x = self.find_father(x)
y = self.find_father(y)
if x == y:
return False
if x<y:
x,y=y,x
self.fathers[x] = y
return True
def is_same_father(self,x,y):
return self.find_father(x)==self.find_father(y)
class Solution:
def trulyMostPopular(self, names: List[str], synonyms: List[str]) -> List[str]:
# print(names[0].split('('))
frq = {
}
for name in names:
a = name.split('(')
b = a[1].split(')')
frq[a[0]]=int(b[0])
hashed = sorted(frq.keys())
n = len(hashed)
ans = defaultdict(int)
uf = UnionFind(n)
for s in synonyms:
ss = s.split(',')
a = ss[0].split('(')[1]
b = ss[1].split(')')[0]
x = bisect_left(hashed,a)
y = bisect_left(hashed,b)
if x<n and y <n:
uf.union(x,y)
for a,b in frq.items():
f = uf.find_father(bisect_left(hashed,a))
ans[f] += b
return [f'{
hashed[a]}({
b})' for a,b in ans.items()]
基于字典的并查集
class UnionFind:
def __init__(self,eles):
self.fathers = {
}
f = self.fathers
for e in eles:
f[e] = e
def find_father(self,x):
f = self.fathers
f.setdefault(x,x)
return self._zip_find_father(x)
def _zip_find_father(self,x):
fathers = self.fathers
if fathers[x] != x:
fathers[x] = self._zip_find_father(fathers[x])
return fathers[x]
def union(self,x,y):
f = self.fathers
f.setdefault(x,x)
f.setdefault(y,y)
x = self.find_father(x)
y = self.find_father(y)
if x == y:
return False
if x<y:
x,y=y,x
self.fathers[x] = y
return True
def is_same_father(self,x,y):
return self.find_father(x)==self.find_father(y)
class Solution:
def trulyMostPopular(self, names: List[str], synonyms: List[str]) -> List[str]:
# 频率入字典
frq = {
}
for name in names:
a = name.split('(')
b = a[1].split(')')
frq[a[0]]=int(b[0])
# 构建并查集
uf = UnionFind(frq.keys())
for s in synonyms:
a,b = s[1:-1].split(',')
uf.union(a,b)
# 构建答案
ans = defaultdict(int)
for a,b in frq.items():
f = uf.find_father(a)
ans[f] += b
return [f'{
a}({
b})' for a,b in ans.items()]
边栏推荐
- 英国德国相继推出5G商用服务,华为成幕后功臣
- 查询字段较多时可以添加普通查询和高级查询两种情况
- 李彦宏遭“泼冷水”热情不减!百度结盟华为麒麟,发布“鸿鹄”芯片
- [Delphi] different platform descriptions of borderstyles of FMX form
- Shell综合应用案例,归档文件
- Robin Lee was "poured cold water" enthusiasm! Baidu allied with Huawei Kirin to release "Honghu" chip
- It is said that HP / Dell / Microsoft / Amazon are considering transferring some hardware production lines outside the mainland
- 易基因|宏病毒组测序技术介绍
- tkinter使用wpf控件
- Nmap installation and use
猜你喜欢

Gartner released the latest market guide for Chinese AI start-ups, and Hongji cyclone was once again rated as a representative enterprise

解决IBGP的水平分割和BGP选路原则

易基因|宏病毒组测序技术介绍

serializable接口的作用是什么?

81. (cesium home) cesium modifies the gray background (default blue)

Experiment 5 OSPF comprehensive experiment

09_ue4进阶_进入下一关并保留血量

BTC和ETH不确定性增强 因加息逼近?美国经济将面临更多痛苦
![[interview brush 101] dynamic planning 1](/img/aa/cf9326d0a4363e96f4e2f1c6079c13.png)
[interview brush 101] dynamic planning 1

How to assemble a registry?
随机推荐
剑指offer46把数字翻译成字符串
Ape tutoring's technological hard power: let AI start from reading children's homework
Task 1 report
Depthwiseseparableconvolution: depthwise convolution and pointwise convolution
ST表、带权并查集
【PyQt5基本控件使用解析】
Kotlin - coroutinecontext
How to praise others gracefully? Try these methods
BUU刷题记3
leetcode 数组类
Build Prometheus automatic monitoring and alarm system from scratch
BGP的基本配置和聚合
The 50 Smartest Companies in the world announced that Chinese manufacturers account for nearly half, and Huawei ranks first
BUU刷题记1
Buu brush inscription 2
When there are many query fields, you can add ordinary query and advanced query
Summary of message queue knowledge points
Execution context and Lexical Environment
What is the role of cache in the storage system of data blocks?
Common operations of ndarray in numpy