HzuHtx


私信TA

用户名:hetangxin123

访问量:41149

签 名:

私はいつまでもレムが好きです。

等  级
排  名 29
经  验 14156
参赛次数 10
文章发表 76
年  龄 0
在职情况 学生
学  校 贺州学院
专  业 软件工程

  自我简介:

写不动,根本写不动

解题思路:

                并查集


#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 7;
struct Node {
	int x, y;
}s[MAXN];
int N, M;
int f[MAXN];
int getf(int n)
{
	if (f[n] == n)
		return n;
	else
		return getf(f[n]);
}
int main()
{
	while (~scanf("%d", &N) && N)
	{
		scanf("%d", &M);
		for (int i = 1; i <= M; i++)
			scanf("%d%d", &s[i].x, &s[i].y);
		for (int i = 1; i <= N; i++)
			f[i] = i;
		int ans = N-1;
		for (int i = 1; i <= M; i++)
		{
			int fx = getf(s[i].x), fy = getf(s[i].y);
			if (fx != fy)
			{
				f[fx] = fy;
				ans--;
			}
		}
		cout << ans << endl;
	}
	return 0;
}


 

0.0分

0 人评分

  评论区