【力扣990. 等式方程的可满足性】并查集(Python3)

题目描述

https://leetcode-cn.com/problems/satisfiability-of-equality-equations/

思路题解

在这里插入图片描述
在这里插入图片描述

["a==b","b==c","c==d","a==f","c==b"]
[a, b, c, d, e, f, g, h, i, j, k, ....]
[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
[1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
[1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
[3, 3, 3, 5, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
[3, 5, 5, 5, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

例如输入"a==b",其实是将b的parent不变,将a的parent设为b的parent。
self.parent[self.find(index1)]=self.find(index2)

class Solution:
    class UnionFind:
        def __init__(self):
            self.parent=list(range(26))
        def find(self,index):
        	# 自己就是根节点
            if index==self.parent[index]:
                return index
            # 查找根节点+路径压缩
            self.parent[index]=self.find(self.parent[index])
            return self.parent[index]
        def union(self,index1,index2):
            self.parent[self.find(index1)]=self.find(index2)
    def equationsPossible(self, equations: List[str]) -> bool:
        uf=Solution.UnionFind()
        for st in equations:
            if st[1]=="=":
                index1=ord(st[0])-ord("a")
                index2=ord(st[3])-ord("a")
                uf.union(index1,index2)
                # print(uf.parent)
        for st in equations:
            if st[1]=="!":
                index1=ord(st[0])-ord("a")
                index2=ord(st[3])-ord("a")
                if uf.find(index1)==uf.find(index2):
                    return False
        return True

在这里插入图片描述
并查集问题整理:
https://blog.csdn.net/anan15151529/article/details/118416802

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值