[模板]匈牙利算法

\(JSOI\)写匈牙利的时候写炸了\(QAQ\),我要好好补基础。

时间复杂度:\(O(m\sqrt{n})\)

#include<set>
#include<cmath>
#include<ctime>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define N 3001
#define M 200001
using namespace std;
struct graph{
    int nxt,to;
}e[M];
int g[N],fr[N],n,m,cnt;
bool u[N];
inline void addedge(int x,int y){
    e[++cnt].nxt=g[x];g[x]=cnt;e[cnt].to=y;
}
inline bool match(int x){
    for(int i=g[x];i;i=e[i].nxt)
        if(!u[e[i].to]){
            u[e[i].to]=true;
            if(!fr[e[i].to]||match(fr[e[i].to])){
                fr[e[i].to]=x;return true;
            }
        }
    return false;
}
inline int hungary(){
    int ret=0;
    for(int i=1;i<=n;i++){
        fill(u+1,u+1+n,false);
        if(match(i)) ret++;
    }
    return ret;
}
inline void init(){
    scanf("%d%d",&n,&m);
    for(int i=1,j,k;i<=m;i++){
        scanf("%d%d",&j,&k);
        addedge(j,k);
    }
    printf("%d",hungary());
}
int main(){
    freopen("hungary.in","r",stdin);
    freopen("hungary.out","w",stdout);
    init();
    fclose(stdin);
    fclose(stdout);
}
posted @ 2016-07-09 17:22  Aireen_Ye  阅读(172)  评论(0编辑  收藏  举报
底部 顶部 留言板 归档 标签
Der Erfolg kommt nicht zu dir, du musst auf den Erfolg zugehen.