Blue bridge cup python and check set

And lookup

Union check set is a tree-type data structure, which is used to deal with the merging and query problems of some disjoint sets

The idea of ​​union search is to use an array to represent the entire forest , and the root node of the tree uniquely identifies a collection . As long as we find the tree root of an element, we can determine which collection it is in .

n,m=map(int,input().split())
p=[i for i in range(n+1)]
def root(x):
    if p[x]!=x:
        p[x]=root(p[x])
    return p[x]
def union(x,y):
    if root(x)!=root(y):
        p[root(x)]=root(y)
for i in range(m):
    z,x,y=map(int,input().split())
    if z==1:
        union(x,y)
    else:
        if root(x)==root(y):
            print('YES')
        else:
            print('NO')


def cost(x,y):
    sums=0
    while x or y:
        if x%10 !=y%10:
            sums+=x%10+y%10
        x=x//10
        y=y//10
    return sums
def root(x):
    if p[x]!=x:
        p[x]=root(p[x])
    return p[x]
def union(x,y):
    if root(x)!=root(y):
        p[root(x)]=root(y)
p=[int(i) for i in range(2022)]
edges=[(i,j,cost(i,j))for i in range(1,2022) for j in range(1,2022)]
edges.sort(key=lambda x:x[2])
ans=0
count=0
for i in edges:
    if root(i[0])!=root(i[1]):
        union(i[0],i[1])
        count+=1
        ans+=i[2]
    if count==2020:
        break
print(ans)
        
        

number of provinces

class Solution:
    def findCircleNum(self, isConnected: List[List[int]]) -> int:
        def find(index: int) -> int:
            if parent[index] != index:
                parent[index] = find(parent[index])
            return parent[index]
        
        def union(index1: int, index2: int):
            parent[find(index1)] = find(index2)
        
        cities = len(isConnected)
        parent = list(range(cities))
        
        for i in range(cities):
            for j in range(i + 1, cities):
                if isConnected[i][j] == 1:
                    union(i, j)
        
        provinces = sum(parent[i] == i for i in range(cities))
        return provinces

regular expression match

import re
class Solution(object):
    def isMatch(self, s, p):
        return re.match(p+'$',s)

You need to add '$' at the end, otherwise the following situation will appear

Guess you like

Origin blog.csdn.net/m0_67105022/article/details/123927850