The Accomodation of Students

The Accomodation of Students

二分图

题目大意:

有n个人,其中一些人相互认识。
佳爷需要将这n个人分成若干个小队(每个小队2人),并使得成员之间相互认识的小队数目最大。
但佳爷不是个随便的人,若无法将这n个人分成两组,且每组中的人相互不认识,那么佳爷将不会进行分队。
请问,佳爷是否需要进行分队呢?

思路:

先判断是否是二分图,用染色法,如果是二分图,用匈牙利算法找到最大匹配数,模板题。

代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 210;

int n, m;
int h[N], e[N * N], ne[N * N], idx;
int match[N];
bool st[N], flag;
int color[N];
void add(int x, int y)
{
    e[idx] = y, ne[idx] = h[x], h[x] = idx ++;
}

bool dfs(int u, int c)
{
    color[u] = c;
    for(int i = h[u]; i != -1; i = ne[i])
    {
        int j = e[i];
        if(!color[j])
        {
            if(!dfs(j, 3 - c)) return false;
        }
        else if(color[j] == c) return false;
    }
    return true;
}

bool find(int x)
{
    for(int i = h[x]; i != -1; i = ne[i])
    {
        int j = e[i];
        if(!st[j])
        {
            st[j] = true;
            if(!match[j] || find(match[j]))
            {
                match[j] = x;
                return true;
            }
        }
    }
    return false;
}


int main()
{
    int n, m;
    while(cin >> n >> m)
    {
        idx = 0;
        memset(h, -1, sizeof h);
        memset(color, 0, sizeof color);
        memset(match, 0, sizeof match);
        flag = true;
        for(int i = 0; i < m; i ++)
        {
            int x, y;
            cin >> x >> y;
            add(x, y);
        }
        for(int i = 1; i <= n; i ++)
        {
            if(!color[i])
            {
                if(!dfs(i, 1))
                {
                    flag = false;
                    break;
                }
            }
        }
        if(!flag) cout << "No\n";
        else{
        int res = 0;
        for(int i = 1; i <= n; i ++)
        {
            memset(st, false, sizeof st);
            if(find(i)) res ++;
        }
        cout << res << endl;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值