牛客多校 - 1 or 2(一般图最大匹配)

讲解:https://blog.csdn.net/qq_45458915/article/details/107306393
代码:

#include<cstdio>
#include<cctype>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=505;
const int maxm=maxn*maxn*2;
int que[maxm],ql,qr,pre[maxn],tim=0;
int h[maxn],ne[maxm],ver[maxm],tot=0;
int match[maxn],f[maxn],tp[maxn],tic[maxn];
int id[maxn][maxn],du[maxn];int cnt=0;
int find(int x) {
	return f[x]==x?f[x]:f[x]=find(f[x]);
}
void add(int u,int v) {
	ver[tot]=v;
	ne[tot]=h[u];
	h[u]=tot++;

}
int lca(int x,int y) {
	for (++tim;;swap(x,y)) if (x) {
		x=find(x);
		if (tic[x]==tim) return x; else 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 (tp[y]==2) tp[y]=1,que[++qr]=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<=cnt;++i) f[i]=i;
	memset(tp,0,sizeof tp),memset(pre,0,sizeof pre);
	tp[que[ql=qr=1]=s]=1; // 1: type A ; 2: type B
	int t=0;
	while (ql<=qr) {
		int x=que[ql++];
		for (int i=h[x],v=ver[i];i!=-1;i=ne[i],v=ver[i]) {
			if (find(v)==find(x) || tp[v]==2) continue; 
			if (!tp[v]) {
				tp[v]=2,pre[v]=x;
				if (!match[v]) {
					for (int now=v,last,tmp;now;now=last) {
						last=match[tmp=pre[now]];
						match[now]=tmp,match[tmp]=now;
					}
					return true;
				} 
				tp[match[v]]=1,que[++qr]=match[v];
			} else if (tp[v]==1) {
				int l=lca(x,v);
				shrink(x,v,l);
				shrink(v,x,l);
			}
		}
	}	
	return false;
}
int main() {
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		memset(h,-1,sizeof h);
		memset(match,0,sizeof match);
		tot=0;cnt=0;		
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&du[i]);
		}
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=du[i];j++)
			{
				id[i][j]=++cnt;
			}
		}
		for (int i=1;i<=m;++i)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			add(cnt+1,cnt+2);add(cnt+2,cnt+1);
			for(int j=1;j<=du[x];j++)
			{
				add(cnt+1,id[x][j]);
				add(id[x][j],cnt+1);
			}
			for(int j=1;j<=du[y];j++)
			{
				add(cnt+2,id[y][j]);
				add(id[y][j],cnt+2);
			}
			cnt+=2;
		}
		int ans=0;
		for (int i=1;i<=cnt;++i) ans+=(!match[i] && aug(i));//n都要改成cnt 
        if(ans*2==cnt) printf("Yes\n");
        else printf("No\n");
	
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值