[PAT]1013 Battle Over Cities

[C++]1013 Battle Over Cities

Battle Over Cities:
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-city2and city1-city3. Then if city1is occupied by the enemy, we must have 1 highway repaired, that is the highway city2-city3.

输入格式:
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.
输出格式:
For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

输入:
3 2 3
1 2
1 3
1 2 3
输出:
1
0
0

题目大意: 大概意思就是有n个城市,当其中一个城市被占领时,需将通往该城市的道路切断,并且联通剩下的城市,问最小需要修多少条路。

解题思路: 相当于求有多少连通分量,假设有n个连通分量,则需要加n-1条边才能使图变成连通图。我们可以把被占领的城市先设置为已被访问,然后在剩下城市中dfs求连通分量。
因为有k个要判断的数据,所以每次输入被占领的城市时,需先初始化used数组(已访问城市数组)为false。

AC代码:

#include<iostream>
#include<cstring>
using namespace std;

int n, m, k;
int mp[1005][1005];
int used[1005];
int res;

void dfs(int x){
	used[x] = 1;
	for(int i = 1; i<=n; i++){
		if(used[i] == 0 && mp[x][i] == 1){
			dfs(i);
		}
	}
}

int main(){
	cin>>n>>m>>k;
	for(int i = 0; i<m; i++){
		int a, b;
		cin>>a>>b;
		mp[a][b] = mp[b][a] = 1;
	}
	
	for(int i = 0; i<k; i++){
		int a;
		cin>>a;
		memset(used, 0, sizeof(used));
		used[a] = 1;
		res = 0;
		for(int j = 1; j<=n; j++){
			if(used[j] == 0){
				res++;
				dfs(j);
			}
		}
		
		cout<<res - 1<<endl;
	}
		
	return 0;
}
发布了63 篇原创文章 · 获赞 8 · 访问量 7182

猜你喜欢

转载自blog.csdn.net/s1547156325/article/details/105210519