【Topic】Maximum Matching of Bipartite Graphs (Hungarian Algorithm)

explain

The Hungarian algorithm, (commonly known as the "sister-finding algorithm"), is a common algorithm for finding the maximum matching of a bipartite graph.
Why is it called "Finding a Girl Algorithm"?
This is because its implementation principle is very similar to looking for girls:
first, we divide a bunch of points into two sides (this is "two points", not the real "two points"):
write picture description here
a line between the two points for boys and girls indicates that they are Like each other
Now we're asking everyone to find the biggest match for girls as possible.
Let's first look at Boy1 (we will call it this way in the future), first look at Girl5: "It's still single, not bad, well, it's her!"
So Girl5 has a boyfriend Boy1. (We marked it red)
write picture description here
Then it was Boy2's turn, of course Girl5 was the first choice, but Girl5 said, "I already have a boyfriend Boy1, if you want me, kick him out."
So Boy2 kicked Boy1 It was lost, Boy1 was very sad, so he went to look for something else, but found that there was nothing he liked, so he came back and kicked Boy2 out. It is impossible for Boy2 to choose Girl5, and we express it as green:
write picture description here
Boy2 had to find another one, but when there was none, he was very sad and couldn't find a girlfriend.
Then at Boy3, he also found Girl6 as his girlfriend:
write picture description here
at Boy4, he first took a fancy to Girl6, so he also kicked Boy3 away, so Boy3 readily gave it to him, "Looking at you so pitiful, let I'll give it to you.", so I went to Girl8 again. In the
write picture description here
end, Boy2 and Girl7 didn't have a match, so they had to not match.
The principle is this.
Summary: Every time you look for a point that can match the current point, if it is selected by someone else, let someone else find another one and occupy it yourself, and if someone else doesn't have it, change it (because we want maximum matching). until all are matched.

bool Matching(int x)
{
    int i,xx,p;
    for (i=1;i<=m;++i)
    {
        if (bz[i]==false)
        {
            bz[i]=true;
            p=las[i];
            las[i]=x;//las表示这个点的前驱。
            if (p==0||Matching(p)) return true;
            las[i]=p;
        }
    }
    return false;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326046560&siteId=291194637