HDU - 1213 How Many Tables

How Many Tables
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 47784 Accepted Submission(s): 23809

Problem Description
Today is Ignatius’ birthday. He invites a lot of friends. Now it’s dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.

Input
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.

Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.

Sample Input
2
5 3
1 2
2 3
4 5

5 1
2 5

Sample Output
2
4

问题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213

问题简述:
举办生日会,让相互认识的人坐在同一张桌子,(A认识B,而B认识C,这里就认为A和C也是认识的),问需要多少张桌子。

问题分析:
涉及到并查集算法

并查集是由一个数组pre[],和两个函数构成的,一个函数为find()函数,用于寻找前导点的,第二个函数是join()用于合并路线的。
详细见代码里的分析。

已AC的代码:

#include
using namespace std;
int m,n, pre[1020], list[1020];//若pre[a]=b,意味着b是a的根节点;list[a]=b,意味着根节点为a的节点有b个。
void prepare(int m)//将根节点初始化。
{
	for (int i = 1;i <= m;i++)
	{
		pre[i] = i;
		list[i] = 1;
	}
}
int find(int k)     //寻找根节点。
{
	int temp = k;
	while (k != pre[k])		
		k = pre[k];
	if (temp != k)     //压缩寻找根节点的路径,将子节点的根节点替换。
	{
		int unreal = pre[temp];
		pre[temp] = k;
		temp = unreal;
	}
	return k;
}
void join(int a, int b)     //将根节点相同的a,b连在一起。
{
	a = find(a);
	b = find(b);
	if (a == b)
		return;
    if (list[a]>=list[b])     //将较短的连接在较长的上面。
	{
		pre[b]=a;
		list[a] += list[b];	
	}
	else
	{
		pre[a] = b;
		list[b] += list[a];	
	}
}

int main()
{
	int a, b,w;
	cin >> w;
	while (w--)
	{
		while (cin >> m >> n && m != 0)
		{
			prepare(m);
			for (int i = 0;i < n;i++)
			{
				cin >> a >> b;
				join(a, b);
			}
			int num = 0;
			for (int i = 1;i <= m;i++)    //若pre[i]的初始值不变,i为根节点,则num++,num为所需桌子数量。
				if (pre[i] == i)
					num++;
			cout << num <<endl;
			

		}

	}
	
}

你可能感兴趣的:(刷题)