uoj #79. 一般图最大匹配 带花树算法

题意

给一个无向图,求该图的最大匹配并输出方案。
n<=500,m<=124750。

分析

妈妈我终于学会了带花树系列。
模板题,具体算法可以看15年的论文,模板的话随便去网上找一个就好了。

代码

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

const int N=505;

int n,m,cnt,last[N],ty[N],tic[N],tim,f[N],match[N],pre[N];
struct edge{int to,next;}e[300005];
queue<int> que;

int read()
{
    int x=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

void addedge(int u,int v)
{
    e[++cnt].to=v;e[cnt].next=last[u];last[u]=cnt;
    e[++cnt].to=u;e[cnt].next=last[v];last[v]=cnt;
}

int find(int x)
{
    if (f[x]==x) return x;
    else return f[x]=find(f[x]);
}

int lca(int x,int y)
{
    for (tim++;;swap(x,y))
        if (x)
        {
            x=find(x);
            if (tic[x]==tim) return x;
            tic[x]=tim;x=pre[match[x]];
        }
}

void shrink(int x,int y,int p)
{
    while (find(x)!=p)
    {
        pre[x]=y;y=match[x];
        if (ty[y]==2) ty[y]=1,que.push(y);
        if (find(x)==x) f[x]=p;
        if (find(y)==y) f[y]=p;
        x=pre[y];
    }
}

bool aug(int s)
{
    for (int i=1;i<=n;i++) f[i]=i,ty[i]=pre[i]=0;
    while (!que.empty()) que.pop();
    que.push(s);ty[s]=1;
    while (!que.empty())
    {
        int x=que.front();que.pop();
        for (int i=last[x],y=e[i].to;i;i=e[i].next,y=e[i].to)
        {
            if (find(x)==find(y)||ty[y]==2) continue;
            if (!ty[y])
            {
                ty[y]=2;pre[y]=x;
                if (!match[y])
                {
                    for (int tmp;y;y=tmp,x=pre[y])
                        tmp=match[x],match[x]=y,match[y]=x;
                    return 1;
                }
                else ty[match[y]]=1,que.push(match[y]);
            }
            else if (ty[y]==1)
            {
                int p=lca(x,y);
                shrink(x,y,p);
                shrink(y,x,p);
            }
        }
    }
    return 0;
}

int main()
{
    n=read();m=read();
    for (int i=1,x,y;i<=m;i++) x=read(),y=read(),addedge(x,y);
    int ans=0;
    for (int i=1;i<=n;i++) if (!match[i]&&aug(i)) ans++;
    printf("%d\n",ans);
    for (int i=1;i<=n;i++) printf("%d ",match[i]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值