匈牙利算法求解最大二分图匹配

今天先贴出代码,后面有空了再来写分析。

代码:

#include<iostream>
#include<vector>
using namespace std;
vector<int>v[1005];
int match[1005];
int visit[1005];
int n1, n2, m;
bool Hungarian(int u)
{
    int i;
    int sz = v[u].size();
    for (i = 0; i < sz;i++)
    {
        if (visit[v[u][i]] == 0)
        {
            visit[v[u][i]] = 1;
            if (match[v[u][i]] == 0 || Hungarian(match[v[u][i]]))
            {
                match[v[u][i]] = u;
                return true;
            }
        }
    }
    return false;
}

int main()
{
    int a,b;
    int i;
    int res;
    while (scanf("%d%d%d", &n1, &n2, &m) == 3)
    {
        for (i = 0; i < m; i++)
        {
            scanf("%d%d", &a, &b);
            v[a].push_back(b+n1);
            v[b+n1].push_back(a);
        }
        res = 0;
        memset(match, 0, sizeof(match));
        for (i = 1; i <= n1; i++)
        {
            memset(visit, 0, sizeof(visit));
            if (Hungarian(i))
                res++;
        }
        printf("%d\n", res);
        for (i = 1; i <= n1 + n2; i++)
            cout << match[i] << endl;
        for (i = 1; i <= n1 + n2; i++)
            v[i].clear();
    }
}
View Code

posted on 2020-11-22 17:25  小叶子曰  阅读(101)  评论(0编辑  收藏  举报

导航