hdu 2444 The Accomodation of Students

The Accomodation of Students

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. 
Input
For each data set: 
The first line gives two integers, n and m(1<n<=200), indicating there are n students and m pairs of students who know each other. The next m lines give such pairs. 


Proceed to the end of file. 


Output
If these students cannot be divided into two groups, print "No". Otherwise, print the maximum number of pairs that can be arranged in those rooms. 
Sample Input
4 4
1 2
1 3
1 4
2 3
6 5
1 2
1 3
1 4
2 5
3 6
Sample Output
No

3

题意:如果不是二分图就输出NO,如果是二分图就求出最大匹配。

判断二分图可以用染色法。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<queue>
#define maxn 210
using namespace std;
int g[maxn][maxn];
int linker[maxn];
bool used[maxn];
int color[maxn];
int n;
bool judge(int u)
{
    for(int i=1;i<=n;i++)
    {
        if(g[u][i]==0)continue;
        if(color[u]==color[i])return false;
        if(color[i]==-1)
        {
            color[i]=!color[u];
            if(!judge(i))
                return false;
        }
    }
    return true;
}
bool dfs(int u)
{
    for(int v=1; v<=n; v++)
    {
        if(g[u][v]&&!used[v])
        {
            used[v]=true;
            if(linker[v]==-1||dfs(linker[v]))
            {
                linker[v]=u;
                return true;
            }
        }
    }
    return false;
}
int hungary()
{
    int res=0;
    memset(linker,-1,sizeof(linker));
    for(int u=1; u<=n; u++)
    {
        memset(used,false,sizeof(used));
        if(dfs(u))res++;
    }
    return res;
}
int main()
{
    int m;
    while(cin>>n>>m)
    {
        memset(g,0,sizeof(g));
        int a,b;
        for(int i=0;i<m;i++)
        {
            cin>>a>>b;
            g[a][b]=g[b][a]=1;
        }
        memset(color,-1,sizeof(color));
        color[1]=1;
        if(!judge(1))
        {
            cout<<"No"<<endl;
            continue;
        }
        cout<<hungary()/2<<endl;
    }
}


原文地址:https://www.cnblogs.com/da-mei/p/9053301.html