(模板)最大匹配——匈牙利算法

例题:51Nod 2006

#include 
#include 
#include 
using namespace std;
const int MAXN = 510;
int uN, vN;
int g[MAXN][MAXN];
int linker[MAXN];
bool used[MAXN];
bool dfs(int u)
{
    for(int v = 0; v < vN; v++)
        if(g[u][v] && !used[v])
        {
            used[v] = true;
            if(linker[v] == -1 || dfs(linker[v]))
            {
                linker[v] = u;
                return true;
            }
        }
    return false;
}
int hungary()
{
    int res = 0;
    memset(linker, -1, sizeof(linker));
    for(int u = 0; u < uN; u++)
    {
        memset(used, false, sizeof(used));
        if(dfs(u)) res++;
    }
    return res;
}
int main()
{
    while(~scanf("%d%d", &uN, &vN))
    {
        if(uN == -1 && vN == -1)
            break;
        memset(g, 0, sizeof(g));
        int from, to;
        while(scanf("%d%d", &from, &to))
        {
            if(from == -1 && to == -1) break;
            g[from][to - uN] = 1;
        }  
        vN -= uN;
        printf("%d\n", hungary()+1);
    }
    return 0;
}

 

你可能感兴趣的:(ACM)