hdu 2444 The Accomodation of Students

acm.hdu.edu.cn/showproblem.php?pid=2444

判断二分图+二分图最大匹配

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAXV = 510;
const int MAXE = 10010;

int mark[MAXV];
int A[MAXV],B[MAXV],t1,t2;
int check[MAXV],ma[MAXV],mb[MAXV];
int n,m,x[MAXE],y[MAXE],G[MAXV][MAXV];


int DFS(int u){
    for(int i=0; i<t2; i++){
        if(!check[B[i]] && G[u][B[i]] > 0){
            check[B[i]] = 1;
            if(mb[B[i]] == -1 || DFS(mb[B[i]])){
                ma[u] = B[i];
                mb[B[i]] = u;
                return 1;
            }
        }
    }
    return 0;
}

void MMC(){
    int res = 0;
    memset(ma, -1, sizeof(ma));
    memset(mb, -1, sizeof(mb));
    for(int i=0; i<t1; i++){
        memset(check, 0, sizeof(check));
        res += DFS(A[i]);
    }
    printf("%d\n",res);
}

int main(){
    while(scanf("%d%d",&n,&m) == 2){
        memset(mark, -1, sizeof(mark));
        bool flag = true;
        for(int i=0; i<m; i++){
            int a,b;
            scanf("%d%d",&a,&b);
            x[i] = a, y[i] = b;
            if(mark[a] == -1 && mark[b] == -1){//一组如果都没染色,那么标记0和1
                mark[a] = 0;
                mark[b] = (mark[a])^1;
            }
            else if(mark[a] == -1 || mark[b] == -1){//如果只有一个没染色,将其染为另一个颜色
                if(mark[a] != -1) mark[b] = (mark[a])^1;
                else mark[a] = (mark[b])^1;
            }
            else//如果都已经染色,那么判断是否出现不是二分图的情况
                if(mark[a] == mark[b]) flag = false;
        }
        if(!flag) {puts("No"); continue;}
        t1 = 0, t2 = 0;
        for(int i=1; i<=n; i++){
            if(!mark[i]) A[t1++] = i;
            else B[t2++] = i;
        }
        memset(G, 0, sizeof(G));
        for(int i=0; i<m; i++){
            if(mark[x[i]]) G[y[i]][x[i]] = 1;
            else G[x[i]][y[i]] = 1;
        }
        MMC();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值