#HDU 2444 The Accomodation of Students

二分匹配,先判断是否是二分图,再求最大匹配。

模板如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <cctype>
#include <fstream>
#define INF 0x3f3f3f3f
#define EPS 1e-6
#define TEST cout<<"stop here"<<endl
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;

//匈牙利算法模板(邻接表)
//ver 0.0.2
const int MAXV = 1000;
int V,E;
vector<int> G[MAXV];
int color[MAXV],match[MAXV];
bool vis[MAXV];

void init(int V){
    memset(color,0,sizeof(color));
    for(int i=0;i<V;i++){
        G[i].clear();
    }//初始化
}

void AddEdge(int u,int v){//建图
    G[u].push_back(v);
    G[v].push_back(u);
}

bool DFS_Color(int u,int c){//二分图判定——涂色
    color[u] = c;
    for(int i=0;i<G[u].size();i++){
        if(color[G[u][i]] == c)
            return false;
        if(color[G[u][i]] == 0 && !DFS_Color(G[u][i],-c)){
            return false;
        }
    }
    return true;
}

bool Judge(){
    for(int i=0;i<V;i++){
        if(color[i] == 0){
            if(!DFS_Color(i,1))
                return false;
        }
    }
    return true;//二分图判定
}

bool DFS_Match(int u){
    vis[u] = true;
    for(int i=0;i<G[u].size();i++){
        int v = G[u][i],w = match[v];
        if(w<0 || !vis[w] && DFS_Match(w)){
            match[u] = v;
            match[v] = u;
            return true;
        }
    }
    return false;//匈牙利算法模板
}

int MaxMatch(){
    int ans = 0;
    memset(match,-1,sizeof(match));
    for(int u=0;u<V;u++){
        if(match[u]<0){
            memset(vis,false,sizeof(vis));
            if(DFS_Match(u)){
                ans++; 
            }
        }
    }
    return ans;//最大匹配
}

void solve(){
    for(int i=0;i<E;i++){
        int u,v;
        cin>> u >> v;
        AddEdge(u-1,v-1);//依照题目,顶点从0还是1开始,本模板是从0开始的。
    }
    if(!Judge()){
        cout<< "No" <<endl;
    }
    else{
        cout<< MaxMatch() <<endl;
    }//输入输出部分
}
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);

    while(cin>> V >> E){
        init(V+1);
        solve();
    }
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值