PAT甲级1013 Battle Over Cities (25 分)

1013 Battle Over Cities (25 分)

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting city​1​​-city​2​​ and city​1​​-city​3​​. Then if city​1​​ is occupied by the enemy, we must have 1 highway repaired, that is the highway city​2​​-city​3​​.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.

Output Specification:

For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

Sample Input:

3 2 3
1 2
1 3
1 2 3

Sample Output:

1
0
0

题目大意:

 有n个城市之间有m条铁路,现在我们关心k个城市,问若k个城市中任意一个城市被占领,问我们至少需要修建多少条铁路将这些城市都连接在一起。

解题思路:

只要对整个图进行dfs,看需要几次dfs后能将所有的城市访问完,最终需要修建铁路数为dfs次数减一。

#include <iostream>
#include <string.h>
#define MAXN 1001
using namespace std;

int n, m, k;
int maps[MAXN][MAXN];       //图邻接矩阵
int city_concern[MAXN];     //所关心的城市
int city_visit[MAXN] = { 0 };

void dfs(int city)
{
	city_visit[city] = 1;
	for (int i = 1;i <= n;i++)
		if (maps[city][i] == 1 && city_visit[i] == 0)
			dfs(i);
}

int main()
{
	cin >> n >> m >> k;
	for (int i = 0;i<m;i++)
	{
		int a, b;
		cin >> a >> b;
		maps[a][b] = 1;
		maps[b][a] = 1;
	}
	for (int i = 0;i<k;i++)
	{
		cin >> city_concern[i];
	}
	for (int i = 0;i<k;i++)
	{
		int cnts = 0;
		for (int i = 1;i <= n;i++) //将所有城市初始化为未访问
		{
			city_visit[i] = 0;
		}
		city_visit[city_concern[i]] = 1; //将被占领的城市设为已访问,使得dfs时不能再经过
		for (int j = 1;j <= n;j++)
		{
			if (!city_visit[j])
			{
				cnts++;
				dfs(j);
			}
		}
		cout << cnts - 1 << endl;
	}
	return 0;
}
发布了56 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lovecyr/article/details/103125893
今日推荐