-------------------------------------------------------------------------------------------------------------------------------------
connected components in undirected graph
题目描述
输入一个简单无向图,求出图中连通块的数目。
输入格式
输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。
以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。
输出格式
单独一行输出连通块的数目。
样例输入
5 3
1 2
1 3
2 4
样例输出
2
深搜:
// Problem#: 12123
// Submission#: 3240308
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 10001;
vector v[maxn];
stack s;
bool visited[maxn];
int res = 0;
void dfs(int begin)
{
if(v[begin].empty())
{
return ;
}
for (int i = 0; i < v[begin].size(); ++i)
{
if(!visited[v[begin][i]])
{
visited[v[begin][i]] = true;
dfs(v[begin][i]);
}
}
}
int main(){
int vertexNum, edgeNum;
while(cin >> vertexNum >> edgeNum)
{
for(int i = 0; i < maxn; i++)
{
v[i].clear();
}
memset(visited,false,sizeof(visited));
res = 0;
int a, b;
for (int i = 1; i <= edgeNum; ++i)
{
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
for (int i = 1; i <= vertexNum; ++i)
{
if(!visited[i])
{
visited[i] = true;
dfs(i);
res++;
}
}
cout<
并查集:
/* 并查集 解决强连通数 */
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 1010;
int p[maxn];
int find(int x) {
return (p[x] < 0) ? x : p[x] = find(p[x]);
}
void unionSets(int x, int y) {
int root1 = find(x);
int root2 = find(y);
if (p[root2] < p[root1])
p[root1] = root2;
else {
if (p[root1] == p[root2])
p[root1]--;
p[root2] = root1;
}
}
int main() {
int n, m;
while (cin >> n >> m) {
int a, b;
int count = 0;
memset(p, -1, sizeof(p));
for (int i = 0; i < m; i++) {
cin >> a >> b;
if (find(a) != find(b))
unionSets(a, b);
}
for(int i = 1; i <=n; i++)
if(p[i] < 0)
count++;
cout<