模板 匈牙利算法

匈牙利算法
模板一:使用邻接矩阵
时间复杂度\(O(n^3)\)

const int maxn=510;
int n,m,line[maxn][maxn],match[maxn],book[maxn];

bool find(int u){
    for(int i=1;i<=m;i++){
        if(line[u][i] && !book[i]){
            book[i]=1;
            if(!match[i] || find(match[i])){
                match[i]=u;
                return true;
            }
        }
    }
    return false;
}

int matching(){
    int res=0;
    for(int i=1;i<=n;i++){
        memset(book,0,sizeof(book));
        if(find(i)) res++;
    }
    return res;
}

模板二:使用邻接表
时间复杂度\(O(nm)\)

const int maxn=5010;
int n,m,head[maxn],nxt[maxn],to[maxn],match[maxn],book[maxn];

bool find(int u){
    if(book[u]) return false;
    book[u]=1;
    for(int i=head[u];i;i=nxt[i]){
        int v=to[i];
        if(match[v]==-1 || find(match[v])){
            match[v]=u;
            return true;
        }
    }
    return false;
}

int matching(){
    int res=0;
    for(int i=1;i<=n;i++){
        memset(book,0,sizeof(book));
        if(find(i)) res++;
    }
    return res;
}

模板题:hdu1083 Courses
    hdu2063 过山车

posted @ 2020-06-21 18:32  fxq1304  阅读(98)  评论(0编辑  收藏  举报