首页 > ACM题库 > HDU-杭电 > hdu 2120 Ice_cream’s world I-并查集-[解题报告]C++
2013
12-29

hdu 2120 Ice_cream’s world I-并查集-[解题报告]C++

Ice_cream’s world I

问题描述 :

ice_cream’s world is a rich country, it has many fertile lands. Today, the queen of ice_cream wants award land to diligent ACMers. So there are some watchtowers are set up, and wall between watchtowers be build, in order to partition the ice_cream’s world. But how many ACMers at most can be awarded by the queen is a big problem. One wall-surrounded land must be given to only one ACMer and no walls are crossed, if you can help the queen solve this problem, you will be get a land.

输入:

In the case, first two integers N, M (N<=1000, M<=10000) is represent the number of watchtower and the number of wall. The watchtower numbered from 0 to N-1. Next following M lines, every line contain two integers A, B mean between A and B has a wall(A and B are distinct). Terminate by end of file.

输出:

In the case, first two integers N, M (N<=1000, M<=10000) is represent the number of watchtower and the number of wall. The watchtower numbered from 0 to N-1. Next following M lines, every line contain two integers A, B mean between A and B has a wall(A and B are distinct). Terminate by end of file.

样例输入:

8 10
0 1
1 2
1 3
2 4
3 4
0 5
5 6
6 7
3 6
4 7

样例输出:

3

点击打开链接

/*

并查集的简单应用,求空间的个数。。

只要两个点有相同的父节点,并且两点间有墙,则就可以构成一个空间。。。。

2013-04-22

*/

#include"stdio.h"
int set[1001];
int find(int x)
{
	if(set[x]==x)return x;
	set[x]=find(set[x]);
	return set[x];
}
int main()
{
	int i;
	int ans;
	int a,b;
	int x,y;
	int n,m;
	while(scanf("%d%d",&n,&m)!=-1)
	{
		for(i=0;i<n;i++)
			set[i]=i;
		ans=0;
		for(i=0;i<m;i++)
		{
			scanf("%d%d",&x,&y);
			a=find(x);
			b=find(y);
			if(a==b)
				ans++;
			else set[b]=a;
		}
		printf("%d\n",ans);
	}
	return 0;
}

解题转自:http://blog.csdn.net/yangyafeiac/article/details/8835414


  1. simple, however efficient. A lot of instances it is difficult to get that a??perfect balancea?? among usability and appearance. I must say that youa??ve done a exceptional task with this. Also, the blog masses quite fast for me on Web explore.

  2. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。

  3. 第一句可以忽略不计了吧。从第二句开始分析,说明这个花色下的所有牌都会在其它里面出现,那么还剩下♠️和♦️。第三句,可以排除2和7,因为在两种花色里有。现在是第四句,因为♠️还剩下多个,只有是♦️B才能知道答案。