1. 程式人生 > >HDU 2444 (判斷二分圖+二分圖最大匹配)

HDU 2444 (判斷二分圖+二分圖最大匹配)

題目連結

題意:首先判斷這個圖是否是二分圖,如果不是二分圖就輸出no,如果是二分圖就輸出最大匹配數

判斷二分圖可以用染色法。。bfs一次就可以

求二分圖最大匹配我用的匈牙利

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>
#include<vector>

typedef long long int ll;
const int  maxn =100000+10;
const int maxm=10000;
const int  mod =998244353;
const int INF=0x3f3f3f3f;

using namespace std;

struct Edge
{
    int to,next;
}edge[maxn];
int head[maxn],tot;

void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
    edge[tot].to=v;edge[tot].next=head[u];
    head[u]=tot++;
}
int linker[maxn];
bool used[maxn];
int uN;
bool dfs(int u)
{
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v=edge[i].to;
        if(!used[v])
        {
            used[v]=true;
            if(linker[v]==-1||dfs(linker[v]))
            {
                linker[v]=u;
                return true;
            }
        }
    }
    return false;
}
int color[501],g[510][510];
bool bfs(int s,int n)
{
    queue<int>q;
    q.push(s);
    color[s]=1;
    while(!q.empty())
    {
        int from=q.front();
        q.pop();
        for(int i=1;i<=n;i++)
        {
            if(g[from][i]&&color[i]==-1)
            {
                q.push(i);
                color[i]=!color[from];
            }
            if(g[from][i]&&color[from]==color[i])
                return false;
        }
    }
    return true;
}

int hungary()
{
    int res=0;
    memset(linker,-1,sizeof(linker));
    for(int u=0;u<uN;u++)
    {
        memset(used,false,sizeof(used));
        if(dfs(u)) res++;
    }
    return res;
}

int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        uN=n;
        init();
        memset(color,-1,sizeof(color));
        memset(g,0,sizeof(g));
        while(m--)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            g[u][v]=g[v][u]=1;
            u--,v--;
            addedge(u,v);
            addedge(v,u);
        }
        bool flag=false;
        for(int i=1;i<=n;i++)
            if(color[i]==-1&&!bfs(i,n))
            {
                flag=true;
                break;
            }
        if(flag) cout<<"No"<<endl;
        else
        {
            cout<<hungary()/2<<endl;
        }
    }
    return 0;
}