Ural 1109 (匈牙利算法)

根据图论基本定里可得:

边覆盖数+最大匹配数=定点数。

所以计算边覆盖数就是答案,即用匈牙利算法解出最大匹配数即可。

ac代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<list>
#include<queue>
#define mm(a,b) memset(a,b,sizeof(a))
#define ACCELERATE (ios::sync_with_stdio(false),cin.tie(0))
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define MAXN 0x3f3f3f3f3f3f3f3f
#define PI acos(-1.0)
#define E exp(1.0)
using namespace std;

//#define debug

const int N=1005;

int e[N][N];
int book[N];
int match[N];
int n,m;

int dfs(int u){
    for(int i=1;i<=m;i++){
        if(!book[i]&&e[u][i]==1){
            book[i]=1;
            if(match[i]==0||dfs(match[i])){
                match[i]=u;
                return 1;
            }
        }
    }
    return 0;
}

int main()
{
    #ifdef debug
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif // debug

    int k;
    ACCELERATE;
    while(cin>>n>>m>>k){
        mm(e,0);
        mm(match,0);
        for(int i=1;i<=k;i++){
            int a,b;
            cin>>a>>b;
            e[a][b]=1;
        }
        int ans=0;
        for(int i=1;i<=n;i++){
            mm(book,0);
            if(dfs(i)) ans++;
        }
        cout<<m+n-ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/81073524
今日推荐