【UOJ#79】一般图最大匹配(带花树)

题面

UOJ

题解

带花树模板题

关于带花树的详细内容

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define ll long long
#define RG register
#define MAX 555
#define MAXL 255555
inline int read()
{
RG int x=0,t=1;RG char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
struct Line{int v,next;}e[MAXL];
int h[MAX],cnt=1;
inline void Add(int u,int v){e[cnt]=(Line){v,h[u]};h[u]=cnt++;}
int match[MAX],pre[MAX],f[MAX],vis[MAX],tim,dfn[MAX];
int n,m,ans;
int getf(int x){return x==f[x]?x:f[x]=getf(f[x]);}
int lca(int u,int v)
{
++tim;u=getf(u);v=getf(v);
while(dfn[u]!=tim)
{
dfn[u]=tim;
u=getf(pre[match[u]]);
if(v)swap(u,v);
}
return u;
}
queue<int> Q;
void Blossom(int x,int y,int w)
{
while(getf(x)!=w)
{
pre[x]=y,y=match[x];
if(vis[y]==2)vis[y]=1,Q.push(y);
if(getf(x)==x)f[x]=w;
if(getf(y)==y)f[y]=w;
x=pre[y];
}
}
bool Aug(int S)
{
for(int i=1;i<=n;++i)f[i]=i,vis[i]=pre[i]=0;
while(!Q.empty())Q.pop();Q.push(S);vis[S]=1;
while(!Q.empty())
{
int u=Q.front();Q.pop();
for(int i=h[u];i;i=e[i].next)
{
int v=e[i].v;
if(getf(u)==getf(v)||vis[v]==2)continue;
if(!vis[v])
{
vis[v]=2;pre[v]=u;
if(!match[v])
{
for(int x=v,lst;x;x=lst)
lst=match[pre[x]],match[x]=pre[x],match[pre[x]]=x;
return true;
}
vis[match[v]]=1,Q.push(match[v]);
}
else
{
int w=lca(u,v);
Blossom(u,v,w);
Blossom(v,u,w);
}
}
}
return false;
}
int main()
{
n=read();m=read();
for(int i=1;i<=m;++i)
{
int u=read(),v=read();
Add(u,v);Add(v,u);
}
for(int i=1;i<=n;++i)if(!match[i])ans+=Aug(i);
printf("%d\n",ans);
for(int i=1;i<=n;++i)printf("%d ",match[i]);puts("");
return 0;
}
05-11 08:00