A1013 Battle Over Cities [图的dfs遍历]

在这里插入图片描述
用图的dfs遍历来算删除结点后连通块的个数,连通块的个数减1就是需要添加的线的个数

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
#include<map>
#include<cstring>
using namespace std;
const int maxv = 1001;
vector<int>g[maxv];
bool vis[maxv];

int currentpoint;
void dfs(int v)
{
	if (v == currentpoint)
		return;
	vis[v] = true;
	for (int i = 0; i < g[v].size(); i++)
	{
		if(vis[g[v][i]]==false)
			dfs(g[v][i]);
	}
}

int main()
{
	int n, m, k;
	scanf("%d%d%d",&n,&m,&k);
	for (int i = 0; i < m; i++)
	{
		int a, b;
		scanf("%d%d",&a,&b);
		g[a].push_back(b);
		g[b].push_back(a);
	}
	for (int j = 0; j < k; j++)
	{
		scanf("%d",&currentpoint);
		memset(vis, false, sizeof(vis));
		int block = 0;
		for (int i = 1; i <= n; i++)
		{
			if (i != currentpoint && vis[i] == false)
			{
				dfs(i);
				block++;
			}
		}
		cout << block - 1 << endl;
	}
}
posted @ 2020-07-29 16:11  _Hsiung  阅读(67)  评论(0编辑  收藏  举报