1013 Battle Over Cities(Connected Components / BFS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LightInDarkness/article/details/84995696

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

Analyze:

    It's a simple question about connected components. We can use BFS or DFS to list the number of connected components. I needn't to explain how to write the code. Be careful, it's necessary to use scanf/printf instead of cin/cout, or you may not pass the last sample.

#include<iostream>
#include<string.h>

using namespace std;

int N, M, K;
int vis[1000], city[1000][1000];

void Dfs(int cur){
	vis[cur] = 1;
	for(int i = 1; i <= N; i++){
		if(vis[i] == 0 && city[cur][i] == 1){
			vis[i] = 1;
			Dfs(i);
		}
	}
}

int main(){
	int c1, c2, occupy, cnt;
	scanf("%d %d %d", &N, &M, &K);
	for(int i = 0; i < M; i++){
		scanf("%d %d", &c1, &c2);
		city[c1][c2] = city[c2][c1] = 1;
	}
	for(int i = 0; i < K; i++){
		cin >> occupy;
		memset(vis, 0, sizeof(int) * 1000);
		vis[occupy] = 1;
		cnt = 0;
		for(int j = 1; j <= N; j++){
			if(vis[j] == 0){
				Dfs(j);
				cnt++;
			}
		}
		printf("%d\n", cnt -1);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/LightInDarkness/article/details/84995696