uoj79 一般图最大匹配 带花树

1 篇文章 0 订阅

Description


从前一个和谐的班级,所有人都是搞OI的。有 n n n个是男生,有 0 0 0个是女生。男生编号分别为 1 , … , n 1,…,n 1,,n
现在老师想把他们分成若干个两人小组写动态仙人掌,一个人负责搬砖另一个人负责吐槽。每个人至多属于一个小组。
有若干个这样的条件:第 v v v个男生和第 u u u个男生愿意组成小组。
请问这个班级里最多产生多少个小组?

Solution


无向图最大匹配板子题

具体而言就是因为存在奇环,所以我们不能直接匈牙利。
但是奇环内部的匹配情况并不影响外部,因此我们把奇环缩掉就可以愉快地继续做了。

我们枚举起点做bfs找增广路,遇到奇环就把奇环内部的点都挂在最浅的点上,找到增广路就暴力翻转
每个点所属的奇环用并查集维护,lca直接暴力跳,这样一套组合拳打下来是O(n^3)的

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))

const int N=505;
const int E=400005;

struct edge {int x,y,next;} e[E];

std:: queue <int> que;

int fa[N],ls[N],tic[N],edCnt,tim;
int match[N],pre[N],tp[N],n;

int read() {
	int x=0,v=1; char ch=getchar();
	for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
	for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
	return x*v;
}

void add_edge(int x,int y) {
	e[++edCnt]=(edge) {x,y,ls[x]}; ls[x]=edCnt;
	e[++edCnt]=(edge) {y,x,ls[y]}; ls[y]=edCnt;
}

int find(int x) {
	return (fa[x]==x)?(x):(fa[x]=find(fa[x]));
}

int get_lca(int x,int y) {
	for (++tim;;std:: 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 lca) {
	while (find(x)!=lca) {
		pre[x]=y; y=match[x];
		if (tp[y]==2) tp[y]=1,que.push(y);
		if (find(x)==x) fa[x]=lca;
		if (find(y)==y) fa[y]=lca;
		x=pre[y];
	}
}

bool bfs(int st) {
	for (;!que.empty();) que.pop();
	rep(i,1,n) fa[i]=i,tp[i]=pre[i]=0;
	tp[st]=1; que.push(st);
	for (;!que.empty();) {
		int x=que.front(); que.pop();
		for (int i=ls[x];i;i=e[i].next) {
			int y=e[i].y;
			if (find(x)==find(y)||tp[y]==2) continue;
			if (!tp[y]) {
				tp[y]=2; pre[y]=x;
				if (!match[y]) {
					for (int now=y,last,tmp;now;now=last) {
						last=match[tmp=pre[now]];
						match[now]=tmp; match[tmp]=now;
					}
					return 1;
				}
				tp[match[y]]=1; que.push(match[y]);
			} else if (tp[y]==1) {
				int lca=get_lca(x,y);
				shrink(x,y,lca);
				shrink(y,x,lca);
			}
		}
	}
	return 0;
}

int main(void) {
	freopen("data.in","r",stdin);
	n=read(); int m=read();
	rep(i,1,m) add_edge(read(),read());
	int ans=0;
	rep(i,1,n) if (!match[i]) {
		ans+=bfs(i);
	}
	printf("%d\n", ans);
	rep(i,1,n) printf("%d ", match[i]);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值