欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 《算法笔记》10.3小节——图算法专题->图的遍历 问题 A: 第一题

《算法笔记》10.3小节——图算法专题->图的遍历 问题 A: 第一题

2025/7/4 1:22:58 来源:https://blog.csdn.net/2401_88085478/article/details/147051618  浏览:    关键词:《算法笔记》10.3小节——图算法专题->图的遍历 问题 A: 第一题
题目描述

该题的目的是要你统计图的连通分支数。

输入

每个输入文件包含若干行,每行两个整数i,j,表示节点i和j之间存在一条边。

输出

输出每个图的联通分支数。

样例输入
1 4
4 3
5 5
样例输出
2

分析: 由于题目没给出范围,只能大概猜测点的范围,数组至少要开到10的6次方。这里我是用并查集计算的。

#include<algorithm>
#include <iostream>
#include  <cstdlib>
#include  <cstring>
#include   <string>
#include   <vector>
#include   <cstdio>
#include    <queue>
#include    <stack>
#include    <ctime>
#include    <cmath>
#include      <map>
#include      <set>
#define INF 0xffffffff
#define db1(x) cout<<#x<<"="<<(x)<<endl
#define db2(x,y) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<endl
#define db3(x,y,z) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<endl
#define db4(x,y,z,r) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<endl
#define db5(x,y,z,r,w) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<", "<<#w<<"="<<(w)<<endl
using namespace std;int findFather(int father[],int x)
{if(father[x]==-1)return -1;int a=x;while(x!=father[x])x=father[x];while(a!=father[a]){int z=a;a=father[a],father[z]=x;}return x;
}void Union(int a,int b,int father[])
{int fa=findFather(father,a),fb=findFather(father,b);if(fa!=fb)father[fa]=fb;return;
}int father[1000010];
bool isroot[1000010];int main(void)
{#ifdef testfreopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);clock_t start=clock();#endif //testfor(int i=0;i<1000010;++i)father[i]=-1;int a,b;while(~scanf("%d%d",&a,&b)){if(father[a]==-1)father[a]=a;if(father[b]==-1)father[b]=b;Union(a,b,father);}for(int i=0;i<1000010;++i){int index=findFather(father,i);if(index!=-1)isroot[index]=1;}int ans=0;for(int i=0;i<1000010;++i)ans+=isroot[i];printf("%d\n",ans);#ifdef testclockid_t end=clock();double endtime=(double)(end-start)/CLOCKS_PER_SEC;printf("\n\n\n\n\n");cout<<"Total time:"<<endtime<<"s"<<endl;        //s为单位cout<<"Total time:"<<endtime*1000<<"ms"<<endl;    //ms为单位#endif //testreturn 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词