Get the size (number of elements) of UnionFind in Python

I'm sorry. Second notebook for myself

Last time I wrote the minimum implementation of Union-Find, and now UnionFind is unmatched! I thought

ABC157 D-Friend Suggestion

https://atcoder.jp/contests/abc157/tasks/abc157_d

AtCoder's problem has made me confused.

The cause is that the implementation to get the size (number of elements) has not been done. Let's reimplement.

Implementation code


    N,Q = map(int,input().split())
    par = [-1]*(N+1)
    def find(x):
        if par[x] < 0:
            return x
        else:
            par[x] = find(par[x]) #Path compression
            return par[x]
    def same(x,y):
        return find(x) == find(y)
    def unite(x,y):
        x = find(x)
        y = find(y)
        if x == y:
            return 0
        else:
          if par[x] > par[y]:
            x,y = y,x
            par[x] += par[y]
            par[y] = x
    def size(x):
        return -par[find(x)]

This is the revised version.

Initialization

    par = [-1]*(N+1)

It should be noted that all the initial initial values are set to -1 and managed.

If you are a parent, you are judged by whether you are negative or not.

Unite

    def unite(x,y):
        x = find(x)
        y = find(y)
        if x == y:
            return 0
        else:
          if par[x] > par[y]:
            x,y = y,x
            par[x] += par[y]
            par[y] = x

Is to take the negative sum of both parents when joining.

By doing so, the child element of par will contain the number of the parent node.

The size (number of elements) of the tree can be held as a negative value in the parent element of par.

Example

For example, in this image, it will be [-5, 0, 0, 0, 0].

size

Now it's clear why the return value of the size function has a minus ‘ー’!

    def size(x):
        return -par[find(x)]

Summary

I was surprised at first that a minus appeared before the return even though I only got the size, but it was very easy to understand once I understood it.

This time, Union Find should be able to match!

Recommended Posts

Get the size (number of elements) of UnionFind in Python
Get the number of specific elements in a python list
How to get the number of digits in Python
[Python] Let's reduce the number of elements in the result in set operations
Get the number of readers of a treatise on Mendeley in Python
Output the number of CPU cores in Python
Get the caller of a function in Python
Get the number of digits
Get Terminal size in Python
[Python] Outputs all combinations of elements in the list
[Python] Get the number of views of all posted articles
Get the URL of the HTTP redirect destination in Python
Get the number of views of Qiita
Get the desktop path in Python
Get the script path in Python
Get the number of Youtube subscribers
Get the desktop path in Python
Get the host name in Python
Python --Find out number of groups in the regex expression
[Homology] Count the number of holes in data with Python
Get the number of occurrences for each element in the list
Get the index of each element of the confusion matrix in Python
Count the number of Thai and Arabic characters well in Python
Check the behavior of destructor in Python
How to check the memory size of a variable in Python
The result of installing python in Anaconda
[python] Get the rank of the values in List in ascending / descending order
The basics of running NoxPlayer in Python
In search of the fastest FizzBuzz in Python
[Python] Get the character code of the file
Get the EDINET code list in Python
Project Euler # 17 "Number of Characters" in Python
Get rid of DICOM images in Python
Get the title and delivery date of Yahoo! News in Python
[Python] Combine all the elements in the array
Get a capture of the entire web page in Selenium Python VBA
Get the number of searches with a regular expression. SeleniumBasic VBA Python
Check the in-memory bytes of a floating point number float in Python
[Python] Calculate the number of digits required when filling in 0s [Note]
Click the Selenium links in order to get the elements of individual pages
Test & Debug Tips: Create a file of the specified size in Python
Get the number of articles accessed and likes with Qiita API + Python
Get a datetime instance at any time of the day in Python
I made a program to check the size of a file in Python
Get the key for the second layer migration of JSON data in python
Get the contents of git diff from python
[python] Check the elements of the list all, any
[Python] Get the files in a folder with Python
Get the weather in Osaka via WebAPI (python)
[Python] Sort the list of pathlib.Path in natural sort
Change the font size of the legend in df.plot
[Python] Get / edit the scale label of the figure
[Python] Get the main topics of Yahoo News
Match the distribution of each group in Python
View the result of geometry processing in Python
Calculate the total number of combinations with python
Make a copy of the list in Python
Find the number of days in a month
Rewriting elements in a loop of lists (Python)
Find the divisor of the value entered in python
[Python] Get the last updated date of the website