【PAT】A1013 Battle Over Cities (25分)


作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB

A1013 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​​ -city3​​ . 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

Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 1010;
int n, m, k, cnt = 0, wayb, waye;
bool flag[maxn];			// 被占领或者访问过就设为1
vector<int> vpath[maxn];
void BFS(int index){		// 以某一个点开始进行BFS
	queue<int> q;
	q.push(index);
	flag[index] = 1;
	cnt++;					// 统计分支个数
	while (!q.empty()){
		int temp = q.front();
		q.pop();
		for (int i= 0; i < vpath[temp].size(); i++){
			if (flag[vpath[temp][i]] == 0){
				q.push(vpath[temp][i]);
				flag[vpath[temp][i]] = 1;
			}
		}
	}
}
int main(){
	scanf("%d %d %d", &n, &m, &k);
	for (int i = 0; i < m; i++){
		scanf("%d %d", &wayb, &waye);	// way_begin and way_end
		vpath[wayb].push_back(waye);
		vpath[waye].push_back(wayb);
	}
	for (int i = 0; i < k; i++){
		scanf("%d", &wayb);
		memset(flag, 0, sizeof(flag));
		flag[wayb] = 1;		// 将该城市设为被占领的城市
		cnt = 0;
		for (int j = 1; j <= n; j++)
			if (flag[j] == 0)	// 找到一个未被占领的城市且未访问过的城市,统计非连通分支数
				BFS(j);
		if (n == 1) printf("0\n");		// 如果是连通图则不用修路
		else	printf("%d\n", cnt - 1);	// 如果不是连通图则需要修的路为分支个数-1
	}
	return 0;
}

Analysis

-要确保城市间的道路在战争时期保持连通。如果一座城市被占领,则周围的路就不能使用,需要建设新的路使得剩下的城市保持连通。

-已知有n个城市,m条路,k个需要被确定如果被占领要修复多少路的城市。

发布了159 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ztmajor/article/details/103840009
今日推荐