码迷,mamicode.com
首页 > 其他好文 > 详细

hdu2444 The Accomodation of Students(判断二分匹配+最大匹配)

时间:2014-08-09 23:16:59      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:hdu   二分匹配   

//判断是否为二分图:在无向图G中,如果存在奇数回路,则不是二分图。否则是二分图。
//判断回路奇偶性:把相邻两点染成黑白两色,如果相邻两点出现颜色相同则存在奇数回路。也就是非二分图。
# include <stdio.h>
# include <string.h>
# include <algorithm>
using namespace std;
int vis[210],map[210][210],cott[210];
int c[210];
int flag,n,m;
void dfs(int i,int color)//染色法判断是否是二分图
{
    for(int j=1; j<=n; j++)
    {
        if(map[i][j])
        {
            if(c[j]==0)
            {
                c[j]=-color;
                dfs(j,-color);
            }
            else if(c[j]==color)
            {
                flag=false;
                return ;
            }
            if(!flag)
                return ;
        }
    }
}
int check()
{
    flag=1;
    memset(c,0,sizeof(c));
    c[1]=1;//一号为黑色,与他相邻的都染为白色
    dfs(1,1);//从一号开始
    return flag;
}

int bfs(int x)
{
    for(int i=1; i<=n; i++)
    {
        if(!vis[i]&&map[x][i])
        {
            vis[i]=1;
            if(!cott[i]|bfs(cott[i]))
            {
                cott[i]=x;
                return 1;
            }
        }
    }
    return 0;
}
int main()
{
    int a,b;
    while(~scanf("%d%d",&n,&m))
    {
        memset(map,0,sizeof(map));
        for(int i=0; i<m; i++)
        {
            scanf("%d%d",&a,&b);
            map[b][a]=map[a][b]=1;
        }
        if(!check())
        {
            printf("No\n");
        }
        else
        {
            int cot=0;
            memset(cott,0,sizeof(cott));
            for(int i=1; i<=n; i++)//以x集合为准找了一遍,又以y集合为准找了一遍,匹配数量增倍
            {
                memset(vis,0,sizeof(vis));
                if(bfs(i))
                    cot++;
            }
            printf("%d\n",cot/2);

        }

    }
    return 0;
}

hdu2444 The Accomodation of Students(判断二分匹配+最大匹配),布布扣,bubuko.com

hdu2444 The Accomodation of Students(判断二分匹配+最大匹配)

标签:hdu   二分匹配   

原文地址:http://blog.csdn.net/lp_opai/article/details/38461329

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!