PAT-1013 Battle Over Cities (25 分)

版权声明:未经过本人同意不得转发 https://blog.csdn.net/weixin_42956785/article/details/84793892

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 city1-city​2and city1-city​3. Then if city​1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2 -city​​ .

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

译文

在战争中让高速公路连接所有城市至关重要。如果一个城市被敌人占领,从该城市出发的所有高速公路都将关闭。如果我们需要修理任何其他高速公路以保持其他城市连通,我们必须立即知道。鉴于标有所有剩余高速公路的城市地图,您应该快速告知需要修复的高速公路数量。

例如,如果我们有3个城市和2个高速公路连接 城市1-城市2,城市1-城市3。然后如果城市1被敌人占领,我们必须有1条公路修好了,这是高速公路城市2和城市3。

输入规格:
每个输入文件包含一个测试用例。每个案例都以包含3个数字的行开头N(< 1 0 0 0),M和K,分别是城市总数,剩余高速公路数量和要检查的城市数量。然后M条线跟随,每条线路用2个整数描述高速公路,这是高速公路连接的城市数量。城市的编号从1到ñ。最后有一行包含K数字,代表我们关注的城市。

输出规格:
对于每一个 K市,如果该城市丢失,需要修复高速公路的数量。

样本输入:
3 2 3
1 2
1 3
1 2 3
样本输出:
1
0
0
解题思路
这题的思路很简单,就是去除被攻占的城市这个点后,算剩下的图一共有几个子连通图。但是呢,小编刚开始的时候用并查集来计算有几个连通图,但遗憾的是,最后一个点运行超时,哈哈哈。所以只能换成深度优先遍历来算有几个子连通图

#include<cstdio>
#include<algorithm>
int citys[1050][1050];
int v[1050];
using namespace std;
//核心算法,深度优先遍历
void DFS(int n, int die,int i)
{
	v[i] = 1;
	for (int j = 1; j <= n; j++)
	{
		if (j != die && citys[i][j] == 1 && v[j] == 0)
		{
			DFS(n, die, j);
		}
	}
}
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);
		citys[a][b] = 1;
		citys[b][a] = 1;
	}
	for (int i = 0; i < k; i++)
	{
		fill(v, v + n + 1, 0);
		int die;
		scanf("%d", &die);
		int count = 0;
		for (int j = 1; j <= n; j++)
		{
			if (v[j] == 0 && j != die)
			{
				count++;
				DFS(n, die, j);
			}
		}
		printf("%d\n", count - 1);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42956785/article/details/84793892
今日推荐