HDU 2444 The Accomodation of Students 二分匹配

来源:互联网 发布:软件研发类期刊 编辑:程序博客网 时间:2024/05/20 01:38

传送门:The Accomodation of Students

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6729    Accepted Submission(s): 3019


Problem Description
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 41 21 31 42 36 51 21 31 42 53 6
 

Sample Output
No3
题意:先判断这些人是否能分成两部分,每个部分的人若有互相认识的人则no,例如:1认识2和3,若2和3认识,则NO,

若分成的两部分是YES,则求出最大匹配数(认识的人才能匹配)

思路:先给第一个人附上值1,则给他的朋友赋值为他的相反数,若两个人为朋友,并且他们的数字相同,则NO。

剩下的就是二分匹配摸板了

AC代码:

#include<iostream>#include <cstdio>#include<algorithm>#include<map>#include<cmath>#include<cstring>#define LL long long#define N 205using namespace std;int n,m,flag;int g[N][N],c[N];int vis[N],line[N];void dfs(int v,int k){    for(int i=1; i<=n; i++)        if(g[v][i])        {            if(!c[i])            {                c[i]=-k;                dfs(i,-k);            }            else if(c[i]==k)                flag=1;            if(flag==1)                return ;        }}int judge(){    memset(c,0,sizeof(c));    flag=0;    c[1]=1;    dfs(1,1);//这里只需判断1,可能是数据比较水。    return flag;}int find(int v){    for(int i=1; i<=n; i++)        if(g[v][i]&&!vis[i])        {            vis[i]=1;            if(!line[i]||find(line[i]))            {                line[i]=v;                return 1;            }        }    return 0;}int main(){    while(~scanf("%d%d",&n,&m))    {        memset(g,0,sizeof(g));        int a,b;        while(m--)        {            scanf("%d%d",&a,&b);            g[a][b]=g[b][a]=1;        }        if(judge())        {            printf("No\n");            continue;        }        memset(line,0,sizeof(line));        int ans=0;        for(int i=1; i<=n; i++)        {            memset(vis,0,sizeof(vis));            if(find(i))                ans++;        }        printf("%d\n",ans/2);//每对朋友算了两次,最后除二。    }}









阅读全文
0 0
原创粉丝点击