SPOJ 4206 二分匹配HK算法

模板题 前向星建边的HK算法

#include <iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cmath>
using namespace std;
const int maxn=50100;
const int maxm=151000;
const int INF=0x3f3f3f3f;
struct EDGE
{
    int b;
    int next;
};
int nx, ny, m;
EDGE edge[maxm];
int edge_num;
int first[maxn];
int cx[maxn],cy[maxn];// cx[i]表示xi对应的匹配,cy[i]表示yi对应的匹配.
int distx[maxn],disty[maxn]; // 层的概念,即在BFS中的第几层.
int que[maxn*10];
int ans;
inline void Init()
{
    fill(cx,cx+maxn,-1);
    fill(cy,cy+maxn,-1);
    fill(first,first+maxn,-1);
    edge_num=0;
    ans=0;
}
inline void AddEdge(int a, int b)
{
    edge[edge_num].b=b;
    edge[edge_num].next=first[a],first[a]=edge_num++;
}
inline bool BFS()
{
    int i,j,k;
    bool flag(0);
    int h,t;
    memset(distx,0,sizeof(distx));
	memset(disty,0,sizeof(disty));
    h=t=0;
    for(i=1;i<=nx;++i)
        if(cx[i]==-1)que[t++]=i;
    for(;h!=t;++h)
    {
		i=que[h];
        for(k=first[i];k!=-1;k=edge[k].next)
        {
            j=edge[k].b;
            if(!disty[j])
            {
                disty[j]=distx[i]+1;
                if(cy[j]==-1)flag=1;
                else distx[cy[j]]=disty[j]+1,que[t++]=cy[j];
            }
        }
    }
    return flag;
}
bool DFS(int i)
{
    int j,k;
    for (k=first[i];k!=-1;k=edge[k].next)
    {
        j=edge[k].b;
        if(disty[j]==distx[i]+1)
        { // 说明j是i的后继结点.
            disty[j]=0; // j被用过了,不能再作为其他点的后继结点了.
            if(cy[j]==-1||DFS(cy[j]))
            {
                cx[i]=j,cy[j]=i;
                return 1;
            }
        }
    }
    return 0;
}
inline void Hopcroft_Karp()
{
    int i,j;
    while(BFS())
        for(i=1;i<=nx;++i)
            if(cx[i]==-1 && DFS(i))++ans;
}
int main(void)
{
//    freopen("Input.txt", "r", stdin);
    int i, j;
    int a, b,p;
    while (scanf("%d%d",&nx,&ny)!=EOF)
    {
        Init();
        scanf("%d",&p);
        for(i=1;i<=p;++i)
        {
            scanf("%d%d",&a,&b);
            AddEdge(a, b);
        }
        Hopcroft_Karp();
        printf("%d\n", ans);
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值