首页 > 其他 > 详细

PAT甲级——A1013 Battle Over Cities

时间:2019-07-15 09:02:39      阅读:100      评论:0      收藏:0      [点我收藏+]

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 (<), 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 Knumbers, 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
分析:添加的最少的路线,就是他们的连通分量数-1,因为当a个互相分立的连通分量需要变为连通图的时候,只需要添加a-1个路线,就能让他们相连。所以这道题就是求去除了某个结点之后其他的图所拥有的连通分量数
使用邻接矩阵存储,对于每一个被占领的城市,去除这个城市结点,就是把它标记为已经访问过,这样在深度优先遍历的时候,对于所有未访问的结点进行遍历,就能求到所有的连通分量的个数~记得因为有很多个要判断的数据,每一次输入被占领的城市之前要把visit数组置为false~~
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 int v[1010][1010];
 6 bool visit[1010];
 7 int n;
 8 void dfs(int node) {
 9     visit[node] = true;
10     for (int i = 1; i <= n; i++) {
11         if (visit[i] == false && v[node][i] == 1)
12             dfs(i);
13     }
14 }
15 int main() {
16     int m, k, a, b;
17     scanf("%d%d%d", &n, &m, &k);
18     for (int i = 0; i < m; i++) {
19         scanf("%d%d", &a, &b);
20         v[a][b] = v[b][a] = 1;
21     }
22     for (int i = 0; i < k; i++) {
23         fill(visit, visit + 1010, false);
24         scanf("%d", &a);
25         int cnt = 0;
26         visit[a] = true;
27         for (int j = 1; j <= n; j++) {
28             if (visit[j] == false) {
29                 dfs(j);
30                 cnt++;
31             }
32         }
33         if(n>1)
34             printf("%d\n", cnt - 1);
35         else
36             printf("%d\n", cnt);
37     }
38     return 0;
39 }

 

 

PAT甲级——A1013 Battle Over Cities

原文:https://www.cnblogs.com/zzw1024/p/11186916.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!