博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
并查集——好朋友
阅读量:4216 次
发布时间:2019-05-26

本文共 722 字,大约阅读时间需要 2 分钟。

在这里插入图片描述

#include
const int maxn = 110;int father[maxn];bool isRoot[maxn];void init(int n){
for(int i = 1; i <= n; i++) {
father[i] = i; isRoot[i] = false; }}int findFather(int x){
while(x != father[x]) {
x = father[x]; } return x;}void Union(int a, int b){
int faA = findFather(a); int faB = findFather(b); if(faA != faB) {
father[faA] = faB; }}int main(){
int n, m, a, b; scanf("%d%d", &n, &m); init(n); for(int i = 0; i < m; i++) {
scanf("%d%d", &a, &b); Union(a, b); } for(int i = 1; i <= n; i++) {
isRoot[findFather(i)] = true; } int ans = 0; for(int i = 1; i <= n; i++) {
ans += isRoot[i]; } printf("%d\n", ans); return 0;}

转载地址:http://hhtmi.baihongyu.com/

你可能感兴趣的文章
《谁的青春不迷茫》
查看>>
有多努力,就有多幸运
查看>>
【Angular】引入BootStrap第三方库
查看>>
创建Angular项目
查看>>
Where there is life, there is hope
查看>>
Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
查看>>
idea启动Tomcat控制台乱码
查看>>
关于Spring
查看>>
SSH插入数据库乱码
查看>>
JSP分页显示重复
查看>>
Linux网络协议栈(一)——Socket入门(1)
查看>>
基于Linux的Socket网络编程的性能优化
查看>>
Linux Network Tuning Linux网络环境性能优化调整
查看>>
Boost socket performance on Linux
查看>>
各种字符串Hash函数
查看>>
perl Sorting Techniques
查看>>
功能自动化测试工具列表大全
查看>>
Perl trim function to strip whitespace from a string
查看>>
一个数是2的幂次方
查看>>
/proc/pid下的相应信息说明
查看>>