HDU-2444-The Accomodation of Students(二分图判定,最大匹配)

链接:

https://vjudge.net/problem/HDU-2444#author=634579757

题意:

There are a group of students. Some of them may know each other, while others don't. For example, A and B know each other, B and C know each other. But this may not imply that A and C know each other.

Now you are given all pairs of students who know each other. Your task is to divide the students into two groups so that any two students in the same group don't know each other.If this goal can be achieved, then arrange them into double rooms. Remember, only paris appearing in the previous given set can live in the same room, which means only known students can live in the same room.

Calculate the maximum number of pairs that can be arranged into these double rooms.

有n个关系,他们之间某些人相互认识。这样的人有m对。
你需要把人分成2组,使得每组人内部之间是相互不认识的。
如果可以,就可以安排他们住宿了。安排住宿时,住在一个房间的两个人应该相互认识。
最多的能有多少个房间住宿的两个相互认识。

思路:

先二分图判定,再二分图最大匹配

代码:

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 2e2+10;
vector<int> G[MAXN];
int Linked[MAXN], Vis[MAXN];
int Color[MAXN];
int n, m;

bool Dfs(int x)
{
    for (int i = 0;i < G[x].size();i++)
    {
        int nextnode = G[x][i];
        if (Vis[nextnode])
            continue;
        Vis[nextnode] = 1;
        if (Linked[nextnode] == -1 || Dfs(Linked[nextnode]))
        {
            Linked[nextnode] = x;
            return true;
        }
    }
    return false;
}

int Solve()
{
    int cnt = 0;
    memset(Linked, -1, sizeof(Linked));
    for (int i = 1;i <= n;i++)
    {
        memset(Vis, 0, sizeof(Vis));
        if (Dfs(i))
            cnt++;
    }
    return cnt;
}

bool Dfsb(int u, int v)
{
    Color[u] = v;
    for (int i = 0;i < G[u].size();i++)
    {
        if (Color[G[u][i]] == v)
            return false;
        if (Color[G[u][i]] == 0 && !Dfsb(G[u][i], -v))
            return false;
    }
    return true;
}

bool Binary()
{
    memset(Color, 0, sizeof(Color));
    for (int i = 1;i <= n;i++)
    {
        if (Color[i] == 0)
        {
            if (!Dfsb(i, 1))
                return false;
        }
    }
    return true;
}

int main()
{
    while (cin >> n >> m)
    {
        for (int i = 1;i <= n;i++)
            G[i].clear();
        int l, r;
        for (int i = 1;i <= m;i++)
        {
            cin >> l >> r;
            G[l].push_back(r);
        }
        if (!Binary())
        {
            cout << "No" << endl;
            continue;
        }
        int cnt = Solve();
        cout << cnt << endl;
    }

    return 0;
}
上一篇:链表


下一篇:VUE学习三,控制元素v-if