[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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章