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
A 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.
A 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.
A 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
Inputcopy | Outputcopy |
---|---|
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
Inputcopy | Outputcopy |
---|---|
5 0 | 5 |
Sample 3
Inputcopy | Outputcopy |
---|---|
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;
}