C - Count Connected Components

Problem Statement

You are given a simple undirected graph with �N vertices numbered 11 to �N and �M edges numbered 11 to �M. Edge �i connects vertex ��ui​ and vertex ��vi​.
Find the number of connected components in this graph.

Notes

simple undirected graph is a graph that is simple and has undirected edges.
A graph is simple if and only if it has no self-loop or multi-edge.

subgraph of a graph is a graph formed from some of the vertices and edges of that graph.
A graph is connected if and only if one can travel between every pair of vertices via edges.
connected component is a connected subgraph that is not part of any larger connected subgraph.

Constraints

  • 1≤�≤1001≤N≤100
  • 0≤�≤�(�−1)20≤M≤2N(N−1)​
  • 1≤��,��≤�1≤ui​,vi​≤N
  • The given graph is simple.
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

�N �M
�1u1​ �1v1​
�2u2​ �2v2​
⋮⋮
��uM​ ��vM​

Output

Print the answer.

Sample 1

InputcopyOutputcopy
5 3
1 2
1 3
4 5
2

The given graph contains the following two connected components:

  • a subgraph formed from vertices 11, 22, 33, and edges 11, 22;
  • a subgraph formed from vertices 44, 55, and edge 33.

Sample 2

InputcopyOutputcopy
5 0
5

Sample 3

InputcopyOutputcopy
4 6
1 2
1 3
1 4
2 3
2 4
3 4
1

 

题解:

1: 加入的查找同时路径压缩

int getf(int v)
{
	if(f[v] != v)
	f[v] = getf(f[v]);
	return f[v];
}

2:加入合并

void merge(int v,int u)
{
	int t1,t2;
	t1 = getf(v);
	t2 = getf(u);

	if(t1 != t2)
	{
		f[t2] = t1;
	}
}

3:判断它的老大是否为自身,是的话加1

代码:

#include<bits/stdc++.h>
using namespace std;
int f[1010];
int n,m;
int getf(int v)
{
	if(f[v] != v)
	f[v] = getf(f[v]);
	return f[v];
}
void merge(int v,int u)
{
	int t1,t2;
	t1 = getf(v);
	t2 = getf(u);

	if(t1 != t2)
	{
		f[t2] = t1;
	}
}
int main()
{
	int i,j,sum,a,b;
		sum = 0;
		cin>>n>>m;
		for(i = 1;i<=n;i ++)
		{
			f[i] = i;
		}
		for(i = 1;i<=m;i ++)
		{
			cin>>a>>b;
			merge(a,b);
		}
		for(i = 1;i<=n;i ++)
		{
			if(f[i] == i)
			{
				sum ++;
			}
		}
		cout<<sum;
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值