匈牙利算法

输入k组匹配, n1为左部点集的数量,n2为右部点集的数量

a为左部点集,b为右部点集

const int MAXN = 5000;
int n1, n2;
int from[MAXN+10];
bool use[MAXN+10];
int tot;

bool match ( int x ){
    for ( int i = 0; i < g[x].size(); ++i ){
        if ( ! use[g[x][i]] ){
            use[g[x][i]] = true;
            if ( from[g[x][i]] == 0 || match ( from[g[x][i]] ) ){
                from[g[x][i]] = x;
                return true;
            }
        }
    }
    return false;
}

int hungary() {
    tot = 0;
    memset ( from, 0, sizeof ( from ) );
    for ( int i = 1; i <= n2; i ++ ){
        memset ( use, 0, sizeof ( use ) );
        if ( match(i) ){
            tot ++;
        }
    }
    return tot;
}

int main()
{
    ios::sync_with_stdio( false );
    int k;
    while ( cin >> k && k ){
        for ( int i = 0; i < MAXN; i ++ )  g[i].clear();
        cin >> n1 >> n2;
        int a, b;
        for ( int i = 0; i < k; i ++ ){
            cin >> a >> b;
            g[a].push_back ( b );
        }
        cout << matching() <


你可能感兴趣的:(模板)