老师我晕课10


私信TA

用户名:1710819010

访问量:10234

签 名:

最后一次

等  级
排  名 479
经  验 4540
参赛次数 7
文章发表 16
年  龄 0
在职情况 学生
学  校 贺州学院
专  业

  自我简介:

非常非常菜的菜鸡

解题思路:
                判断连通图,构建并查集即可
注意事项:


参考代码:

#include <iostream>
#include <cstring>
using namespace std;
int arr[1050];
bool vis[1050];
int root(int x) {
	int r = x;
	while (arr[r] != r) { //寻找祖先
		r = arr[r];
	}
	int i = x, j;
	while (i != r) {	//路径压缩
		j = arr[i];
		arr[i] = r;
		i = j;
	}
	return r;
}
int main() {
	int n, m;
	while (cin >> n >> m && n && m) {
		for (int i = 1; i <= 1050; i++) //初始化
			arr[i] = i;
		memset(vis, 0, sizeof(vis));
		for (int i = 1; i <= m; i++) { 
			int a, b;
			cin >> a >> b;
			int fx = root(a);
			int fy = root(b);
			arr[fx] = fy;
		}
		for (int i = 1; i <= n; i++) {//标记祖先
			vis[root(i)] = 1;
		}
		int ans = 0;
		for (int i = 1; i <= n; i++) { // 查找有多少个祖先,则连通图则有几个
			if (vis[i]) {
				ans++;
			}
		}
		if (ans == 1)
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}


 

0.0分

3 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区