这道题题意是说给出一张图的点和边,无向图。
去掉一个点 问如果要使剩余的点连通 ,最少需要再连通几条边。
实质就是求连通子集的数量,然后连通子集的数量-1即为结果。
这里可以用三种放法 bfs dfs 和并查集。
论效率来讲的话当然是并查集最快。以这道题的数据量来看 dfs要比bfs快些。但是我不大喜欢用dfs做这种题。dfs做起来太无脑。
bfs暴力模拟简单明了
给出bfs代码
#include<iostream>
#include<cstdio>
#include<map>
#include<cmath>
#include<string>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
int vis[1010];
int rel[1010][1010];
int main() {
int n, m, k;
cin >> n >> m >> k;
for (int i = 0; i < m; i++)
{
int f, t;
cin >> f >> t;
rel[f][t] =rel[t][f]= 1;
}
for (int i = 0; i < k; i++)
{
int cur;
cin >> cur;
memset(vis, 0, sizeof(vis));
vis[cur] = 1;
int cnt = 0;
queue<int> q;
for (int j = 1; j <= n; j++)
{
if (!vis[j])
{
vis[j] = 1;
cnt++;
q.push(j);
while (!q.empty())
{
int current = q.front();
q.pop();
for (int m = 1; m <= n; m++)
{
if (!vis[m] && rel[m][current])
{
vis[m] = 1;
q.push(m);
}
}
}
}
}
cout << cnt - 1 << endl;
}
return 0;
}