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

来源:互联网 发布:it人才培养方 编辑:程序博客网 时间:2024/05/16 01:03
//判断是否为二分图:在无向图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;}

1 0
原创粉丝点击