Maximum matching of bipartite graphs (Hungarian algorithm & Dinic algorithm)

Maximum matching of bipartite graphs:

Given a bipartite graph, there are several nodes on the left, several nodes on the right, the node on the left thinks of matching the node on the right, each node on the left has several objects that can be selected, and each node on the left can only be selected A right node, each right node can only be selected once. Now ask you how many nodes on the left can match?

Generally speaking, there are a group of people and a bunch of prizes. Everyone has their favorite prize. There is only one prize of each kind. Ask how much you can get your favorite prize (each person can only get one, And each person may have multiple favorite prizes)?

Hungarian algorithm:

The approach of the Hungarian algorithm is to first match each left node, and if there is a right node that has not been matched, it will match directly. Otherwise, ask the matcher of the matched node on the right to see if it has other options.
topic

#include<bits/stdc++.h>

using namespace std;
const int maxn = 1e5 + 5;
int n1,n2,u,v,m,mat[maxn],st[maxn];//mat数组表示第i个节点是否被匹配,如果是0则是没被匹配
int h[maxn],e[maxn],nex[maxn],cnt = 1;

void add(int a, int b){
    
    
    e[cnt] = b;
    nex[cnt] = h[a];
    h[a] = cnt++;
}

int findE(int x){
    
    
    for(int i = h[x]; i != 0; i = nex[i]){
    
    
        int endd = e[i];
        if(!st[endd]){
    
    
            st[endd] = 1;
            if(mat[endd] == 0 || findE(mat[endd])){
    
    //没被匹配,或者匹配的人还有别的选择,则当前节点可以匹配此节点
                mat[endd] = x;
                return 1;
            }
        }
    }
    return 0;
}

int main(){
    
    
    cin >> n1 >> n2 >> m;
    int a,b,ans = 0;
    while(m--){
    
    
        cin >> a >> b;
        add(a,b);
    }
    for(int i = 1; i <= n1; i++){
    
    
        memset(st,0,sizeof st);
        if(findE(i))ans++;//匹配到了匹配数目就加一
    }
    cout << ans << endl;
}

Dinic algorithm

Dinic is a network flow algorithm and can also be used for bipartite graph matching. You can connect the node on the right to the sink point, the node on the left to the source point, and then connect the left and right related ones, so the graph is built and the capacity of each edge is 1.

It can be found that the node on the right is connected to the sink point, that is, to reach the sink point, you need to pass the point on the right, and to reach the point on the right, you need to pass the point on the left, so the matching effect can be achieved.
Seating Arrangement A
relatively naked question, it’s just right to write Dinic

Guess you like

Origin blog.csdn.net/qq_36102055/article/details/107384118