匈牙利算法学习

学习出https://blog.csdn.net/sunny_hun/article/details/80627351

题:poj1325

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
inline int read(){
    int sum=0,x=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')
            x=0;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
        sum=(sum<<1)+(sum<<3)+(ch^48),ch=getchar();
    return x?sum:-sum;
}
inline void write(int x){
    if(x<0)
        putchar('-'),x=-x;
    if(x>9)
        write(x/10);
    putchar(x%10+'0');
}
const int M=102;
int match[M],mp[M][M],book[M];
int n,m,t;
bool dfs(int x){
    for(int i=1;i<=m;i++){
        if(mp[x][i]&&!book[i]){
            book[i]=1;
            if(!match[i]||dfs(match[i])){
                match[i]=x;
                return true;
            } 
        }
    }
    return false;
}

void init(){
    int L=max(n,m);
    for(int i=0;i<=L;i++){
        for(int j=0;j<=L;j++)
            mp[i][j]=0;
        match[i]=0;
    }
}
int main(){
    while(~scanf("%d",&n)){
        if(!n)
            break;
        m=read(),t=read(); 
        init();
        while(t--){
            int i=read();
            int x=read();
            int y=read();
            mp[x][y]=1;
        }
        int ans=0;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++)
                book[j]=0;
            if(dfs(i))
                ans++;
        }
        write(ans);
        putchar('\n');
    }
    return 0;
}
View Code

 

posted @ 2019-06-07 13:39  starve_to_death  阅读(139)  评论(0编辑  收藏  举报