KSzsh

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Count Connected Components(判断连通块数量)

题目描述:

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

输入描述:

NM

u1v1

u2v2

...

umvm

输出描述:

Print the answer.

样例1:

input:

5 3
1 2
1 3
4 5

ouput:

2

样例2:

input:

5 0

output:

5

样例3:

input:

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

ouput:

1

AC代码:

// 方法一:并查集
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
int f[N];
int d[N];
int find(int x)
{
if(x != f[x])
f[x] = find(f[x]);
return f[x];
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i ++)
f[i] = i;
int ans = 0;
for(int i = 1; i <= m; i++)
{
int a, b;
cin >> a >> b;
int fa = find(a), fb = find(b);
if(fa != fb)
{
f[fa] = fb;
}
}
for(int i = 1; i <= n; i ++)
{
int fi = find(i);
if(fi == i)
ans ++;
}
cout << ans << '\n';
return 0;
}
// 方法二:邻接表+DFS
#include <bits/stdc++.h>
using namespace std;
const int N = 110, M = 1e5 + 10;
int T = 1;
int n, m;
bool st[N];
int h[N], e[M], ne[M], idx;
void dfs(int u)
{
st[u] = 1;
for(int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if(!st[j])
{
dfs(j);
}
}
}
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void solve()
{
cin >> n >> m;
memset(h, -1, sizeof h);
for(int i = 1; i <= m; i ++)
{
int a, b;
cin >> a >> b;
add(a, b);
add(b, a);
}
int ans = 0;
for(int i = 1; i <= n; i ++)
if(!st[i])
{
ans ++;
dfs(i);
}
cout << ans << '\n';
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
// cin >> T;
// scanf("%d", &T);
while (T--)
solve();
return 0;
}
// 方法三:vector+DFS
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
// 也可以用vector<int> g[N];
vector<vector<int>> g(N);
// bool st[N];
vector<int> vis(N);
void dfs(int u)
{
vis[u] = 1;
for (auto j : g[u])
{
if (vis[j])
continue;
dfs(j);
}
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
-- u, -- v;
g[u].push_back(v);
g[v].push_back(u);
}
int ans = 0;
for (int i = 0; i < n; i++)
{
if (!vis[i])
{
ans++;
dfs(i);
}
}
cout << ans << "\n";
return 0;
}

posted on   KSzh  阅读(69)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示