您的位置:首页 > 其它

hdu 2120 Ice_cream's world I (简单并查集 + 判环)

2015-08-12 16:18 573 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2120



【题目大意】

富裕的女王 要给ACMER分地,女王的土地中有很多瞭望塔,女王命令下人在瞭望塔(watchtower) 与瞭望塔之间建立笔直的围墙,被围墙圈起来的土地可以用来奖励ACMER,但是女王智商捉急,不知道最多能奖励多少ACMER,请你来帮忙。

通过并查集的Union操作就可以实现瞭望塔之间的联通,如果两个瞭望塔所在根节点相同,说明有环,非常简单的问题

【源代码】

#include<cstdio>
using namespace std;
const int maxn = 1010;
int father[maxn];
void init(){
	for(int i=0;i<maxn;i++)
		father[i]=i;
}
int Find(int x){
	int rt = x;
	while(rt!=father[rt])
		rt=father[rt];
	while(x!=rt){
		int tmp = father[x];
		father[x] = rt;
		x=tmp;
	}
	return rt;
}
int Union(int x, int y){
	int xr = Find(x);
	int yr = Find(y);
	if(xr == yr) return 1; //根节点相同, 说明成环
	father[xr] = yr;
	return 0;
}
int main(){
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF){
		init();
		int a,b;
		int ans= 0;
		for(int i=0;i<m;i++){
			scanf("%d%d",&a,&b);
			ans+=Union(a,b);
		}
		printf("%d\n",ans);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: