第二次周赛HDU-1213题解

问题链接:HDU-1213

问题简述

Ignatius要过生日,邀请朋友来,需要计算所需要的桌子数,认识的同学只能一起坐在同一桌,如果A认识B,B认识C,那么A,C也算相互认识。首先第一行个输入n,表示有n组数据,每组数据第一行包含两个输x,y,x表示朋友的总人数,y表示有y组对应关系,接下来y行每行表示一组对应关系,最后输出所需桌子数。

思路

并查集算法,最后求出桌子数即可。

AC通过的C++语言程序如下:

#include<iostream>
#include<vector>
int find(int);
void build(int, int);
using namespace std;
int a[1000];
int main()
{
	int t;
	cin >> t;
	for (int i = 0; i < t; i++)
	{
		int n, m, p = 0;
		cin >> n >> m;
		for (int j = 0; j < n; j++)
			a[j] = j;
		for (int j = 0; j < m; j++)
		{
			int x, y;
			cin >> x >> y;
			build(x-1, y-1);
		}
		for (int j = 0; j < n; j++)
			if (a[j] == j) p++;
		cout << p << endl;
	} 
	return 0;
}
int find(int t)
{
	if (a[t] == t) return t;
	else return find(a[t]);
}
void build(int s, int t)
{
	if (find(s) != find(t))
		a[find(s)] = find(t);
}

猜你喜欢

转载自blog.csdn.net/weixin_43970556/article/details/85073251
今日推荐