A1013 Battle Over Cities (25 point(s))

DFS求连通图

1. 原文

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:

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

Sample output:

1
2
3
1
0
0

2. 解析

遍历每个节点和它的连通点,若整个连通,则cnt=1;不连通,cnt则为几个连通图的代表,连通则需要cnt-1条边

3. AC代码

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
48
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=1010;
vector<int> v[maxn];
bool visit[maxn]={false};
void dfs(int root)
{
visit[root]=true;
for (int i = 0; i < v[root].size(); ++i)
{
if (visit[v[root][i]]==false)
{
dfs(v[root][i]);
}
}

}
int main()
{
int n,m,k;
scanf("%d%d%d",&n,&m,&k);
int a,b;
for (int i = 0; i < m; ++i)
{
scanf("%d%d",&a,&b);
v[a].push_back(b);
v[b].push_back(a);
}
for (int i = 0; i < k; ++i)
{
scanf("%d",&a);
int cnt=0;
fill(visit,visit+maxn,false);
visit[a]=true;
for (int j = 1; j <= n; ++j)
{
if (visit[j]==false)
{
dfs(j);
cnt++;
}
}
printf("%d\n",cnt-1);
}
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1013/
  • 发布时间: 2019-09-03 12:35
  • 更新时间: 2021-10-29 13:59
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!