Hungary(匈牙利算法)——二分图最大匹配

  在复习匈牙利算法的时候,发现这么一篇介绍匈牙利算法的文章,非常通俗易懂,所以就借鉴过来了。

     复杂度:邻接矩阵:O(v^3)邻接表:O(V*E)

  附上链接:趣写算法系列之--匈牙利算法

  下面就附上代码吧:

  

int maxn;//maxn 为x、y集合的最大顶点数
int xmatch[maxn]; //xmatch[i]表示X集合中的i在Y集合中对应的匹配
int ymatch[maxn]; //ymatch[i]表示Y集合中的i在X集合中对应的匹配

int map[maxn][maxn];  //邻接矩阵,若i与j不相连,则为0
bool used[maxn];   //用于标记是否某点被遍历过
int n,m; //X集合个数n,Y集合个数m

bool find(int x){
    for(int i=0;i<m;i++){
        if(map[x][i] && !used[i]){
            used[i]=1;
            if(ymatch[i]=-1 || find(ymatch[i])){
                    ymatch[i]=x;
                    return true;
            }
        }
    }
    return false;
}

int hungary(){
    int cnt=0; //最大匹配数目
    memset(ymatch,-1,sizeof(ymatch));
    for(int i=0;i<n;i++){
        memset(used,0,sizeof(used));
        if(find[i]){
            cnt++;
        }
    }
    return cnt;
}
View Code
原文地址:https://www.cnblogs.com/chenxiwenruo/p/4511166.html