您的位置:首页 > 其它

hdu 2444 The Accomodation of Students 二分图判定+二分匹配个数

2015-11-17 13:27 239 查看
[code]#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int MAXN=1024;
const int MAXM=1024*100;

struct Edge
{
    int to,next;
} edge[MAXM];
int head[MAXN],tot,mx[MAXN],cx[MAXN],cy[MAXN],mk[MAXN];

void addedge(int from,int to)
{
    edge[tot].to=to;
    edge[tot].next=head[from];
    head[from]=tot++;
}

void init()
{
    memset(head,0xff,sizeof(head));
    tot=0;
}

int dfs(int u)
{
    for(int i=head[u]; i!=-1; i=edge[i].next)
    {
        int v=edge[i].to;
        if(!mk[v])
        {
            mk[v]=1;
            if(cy[v]==-1||dfs(cy[v]))
            {
                cx[u]=v;
                cy[v]=u;
                return 1;
            }
        }
    }
    return 0;
}

int Maxmatch(int n)
{
    int res=0;
    memset(cx,0xff,sizeof(cx));
    memset(cy,0xff,sizeof(cy));
    for(int i=1; i<=n; i++)
    {
        if(cx[i]==-1)
        {
            memset(mk,0,sizeof(mk));
            res+=dfs(i);
        }
    }
    return res;
}

int color[MAXN];
int bipartite(int u)
{
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v=edge[i].to;
        if(color[u]==color[v]) return 0;
        if(!color[v])
        {
            color[v]=3-color[u];
            if(!bipartite(v))
                return 0;
        }
    }
    return 1;
}

int main()
{
    int i,j,n,m,u,v;
    while(~scanf("%d%d",&n,&m))
    {
        init();
        for(i=0;i<m;i++)
        {
            scanf("%d%d",&u,&v);
            addedge(u,v);
            addedge(v,u);
        }
        memset(color,0,sizeof(color));
        color[1]=1;
        int ans=bipartite(1);
        if(ans==0) {printf("No\n");continue;}
        ans=Maxmatch(n);
        printf("%d\n",ans/2);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: