HDU2444 The Accomodation of Students 染色法判断二分图+二分图匹配

第一次用染色法。。网上找了份bfs邻接表的模板就用了2333

附上AC代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

const int MAX=205;
int n,m,l,r;
struct edge
{
    int to,next;
}e[100*MAX];
int tol,head[MAX];
int link[MAX];
bool vis[MAX];

void init()
{
    tol=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
    e[tol].to=v;e[tol].next=head[u];
    head[u]=tol++;
}
bool dfs(int u)
{
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].to;
        if(!vis[v])
        {
            vis[v]=true;
            if(link[v]==-1||dfs(link[v]))
            {
                link[v]=u;
                return true;
            }
        }
    }
    return false;
}
int hungry()
{
    int ans=0;
    l=r=n;
    memset(link,-1,sizeof(link));
    for(int u=0;u<l;u++)
    {
        memset(vis,false,sizeof(vis));
        if(dfs(u))
            ans++;
    }
    return ans;
}

int color[MAX];
bool Color()//BFS染色 判断是不是二分图
{
    memset(vis,false,sizeof(vis));
    memset(color,0,sizeof(color));
    queue<int>q;
    int x=0;
    q.push(x);
    vis[x]=1;
    color[x]=1;
    while(!q.empty())
    {
        int p=q.front();
        q.pop();
        for(int i=head[p];i!=-1;i=e[i].next)
        {
            int v=e[i].to;
            if(!vis[v])
            {
                color[v]=1-color[p];//总是让相邻两个点的color一个为1一个为0
                vis[v]=true;
                q.push(v);
            }
            else if(vis[v]==true)
                if(color[v]==color[p])
                    return false;//相邻两点,颜色相同
        }
    }
    return true;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        init();//注意!!!
        int x,y;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&x,&y);
            x--,y--;
            addedge(x,y);
            //addedge(y,x);
        }
        if(!Color())
        {
            printf("No\n");
            continue;
        }
        int ans=hungry();
        printf("%d\n",ans);//若连两次边,记得除2
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cc_Sonia/article/details/81902292
今日推荐