PTA甲级——1013

1013 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-city2 and city1- city3. Then if city1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2-city3.

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:

1
2
3
4
3 2 3
1 2
1 3
1 2 3

Sample Output:

1
2
1
0

思路

​ 大致题意:我们处于一场战争中,首先给出一些想联通的城市,给出各个城市之间的路径,然后给出k个数,每输入一个数就表示编号对应的城市被敌军占领,这个城市就不可以再通信了,这时候我们需要找最少需要再搭建多少条路才可以让剩余的城市两连通。

​ 思路:这道题首先从题意上知道这是一个无向图。那么我们是不是可以这样想,我们把可以联通的城市放在一个集合里面,那么我们需要修建的路最少是不是就是集合的个数-1就ok了,下面我们需要想的就是如何表示这个集合,第一种思路你可以选择使用使用数组表示,但是这里会存在一个问题,用数组表示我们会很难判断两个城市是否在同一个城市里,判断的时间复杂度可能会有点高。另外一种思路其实也很快可以想到,就是并查集!

  • 对于联通的两个城市就放在一个集合里面
  • 然后当我们枚举敌人占领城市的时候就可以包含敌人占领城市的编号的路径不进行操作,这样我们就可以得到一系列集合,cnt - 1即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e3 + 10;
const int M = 5e5 + 10;
int p[N];
typedef struct {
int a, b;
}Node;
Node e[M];

int find(int x){
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}

int main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int n, m, k;
cin >> n >> m >> k;
for (int i = 1; i <= m; i++) {
cin >> e[i].a >> e[i].b;
}

for (int i = 1; i <= k; i++){
memset(p, 0, sizeof p);
int k, cnt = n - 1;
cin >> k;
for (int j = 1; j <= n; j++) {
p[j] = j;
}

for (int i = 1; i <= m; i++){
if (e[i].a != k && e[i].b != k) {
int aa = find(e[i].a), bb = find(e[i].b);
if (aa != bb) {
p[aa] = bb;
cnt--;
}
}
}

cout << cnt - 1 << '\n';
}

}