BZOJ 1854 [Scoi2010]游戏 - 二分图匹配/并查集

考察内容:二分图匹配/并查集


二分图匹配:
考虑到二分图的特性为不能重复匹配,题意中恰有武器的两个属性只能选择一个的特性,于是联想到二分图最大匹配,将武器编号和其威力值相连,威力值有小到大调用find函数,若无法匹配则终止输出答案


并查集:

可以想象武器作为路径将两种威力值相连,相连需要一种能够体现集合性质的数据结构,于是想到并查集。并查集维护每个集合的最大值,若不成环,则必有一个节点无法访问到,于是选择最大节点为无法访问节点,而对于每一个武器两个节点来说,若两个节点已经在一个集合里,则此集合必成环,此时将集合最大值vst数组进行标记,表示可以取到。最后由小到大查询每个节点的集合,若此节点恰为集合最大值,则终止循环输出答案,特别注意vst数组有标记的最大节点可以取到,所以提前continue。


#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm> 

using namespace std;

#if true //并查集 

const int maxn=10010;

int n;
int fa[maxn];
int maxnum[maxn];
bool vst[maxn];

int find(int x)
{
	return fa[x]==x?x:fa[x]=find(fa[x]);
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<maxn;i++)fa[i]=maxnum[i]=i;
	for(int i=1;i<=n;i++)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		a=find(a);
		b=find(b);
		if(a==b)
			vst[maxnum[a]]=true;
		else
		{
			fa[a]=b;
			maxnum[b]=max(maxnum[b],maxnum[a]);
		}
	}
	int i;
	for(i=1;i<maxn;i++)
	{
		int tmp=find(i);
		if(vst[i])continue;
		if(i==maxnum[tmp])break;
	}
	printf("%d",i-1);
}

#else //二分图匹配 

const int maxn=1000010;

struct edge
{
	int to,next;
}e[maxn<<1];

int n,maxi,T;
int head[maxn];
int match[maxn];
int vst[maxn];

inline void insert(int a,int b)
{
	static int cnt=0;
	e[++cnt].to=b;e[cnt].next=head[a];head[a]=cnt;
}
bool find(int x)
{
	for(int i=head[x];i;i=e[i].next)
	{
		int y=e[i].to;
		if(vst[y]==T)continue;
		vst[y]=T;
		if(!match[y]||find(match[y]))
		{
			match[y]=x;
			return true;
		}
	}
	return false;
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		insert(a,i);
		insert(b,i);
		maxi=max(maxi,max(a,b));
	}
	for(int i=1;i<=maxi;i++)
	{
		T++;
		if(!find(i))
		{
			printf("%d",i-1);
			return 0;
		}
	}
	printf("%d",maxi);
} 
#endif




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值