HDU-2444 The Accomodation of Students

先看图是否是二分图,用染色来判断即可,两种颜色,相邻的点染不同的颜色,没有冲突即可

dfs染色分完之后,再用匈牙利算法求最大匹配

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
const int N=200+10;
const int M=80000+10;
struct Edge
{
    int to,nxt;
}edge[M];
int tot,first[N];
void addedge(int u,int v)
{
    edge[tot].to=v;
    edge[tot].nxt=first[u];
    first[u]=tot++;
}
void init()
{
    tot=0;
    memset(first,-1,sizeof(first));
}
int linker[N];
bool used[N];
bool dfs(int u)
{
    for(int i=first[u];i!=-1;i=edge[i].nxt)
    {
        int v=edge[i].to;
        if(!used[v])
        {
            used[v]=true;
            if(linker[v]==-1||dfs(linker[v]))
            {
                linker[v]=u;
                return true;
            }
        }
    }
    return false;
}
int uN;
int col[N];
int hungary()
{
    int res=0;
    memset(linker,-1,sizeof(linker));
    for(int i=1;i<=uN;i++)
    {
        if(col[i]==-1) continue;
        memset(used,false,sizeof(used));
        if(dfs(i)) res++;
    }
    return res;
}
bool dfs0(int u,int c)
{
    if(col[u])
    {
        if(col[u]==c) return true;
        else return false;
    }
    col[u]=c;
    for(int i=first[u];i!=-1;i=edge[i].nxt)
    {
        int v=edge[i].to;
        if(!dfs0(v,-c)) return false;
    }
    return true;
}
bool solve()
{
    memset(col,0,sizeof(col));
    for(int i=1;i<=uN;i++)
        if(!col[i]&&!dfs0(i,1)) return false;
    return true;
}
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        init();
        int a,b;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&a,&b);
            addedge(a,b);
            addedge(b,a);
        }
        uN=n;
        if(!solve()) printf("No\n");
        else printf("%d\n",hungary());
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值