原文链接:http://kakazai.cn/index.php/Kaka/Pat/query/id/103
题目
题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805500414115840
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:
3 2 3
1 2
1 3
1 2 3
Sample Output:
1
0
0
题意分析
- 题意
现有一些城市,城市间有高速相连。如果某城市被敌人占领,那么跟它相连的高速都会被毁掉,剩下的城市可能因此不连通。问,如果占领某城市后,剩余的城市至少要搭建多少条高速才能够连通。
- 分析
将城市看成点,高速看成边。若去掉某个点后,跟它相连的边都会被去掉。问题变成,如果去掉某个点,剩下的图中会有多少个连通块。
知识点与坑点
- 知识点
1)DFS,图的连通性
- 坑点
1)
一、DFS
算法思路
1 若某个点要去掉,则将它设为已访问
2 在剩下的点中,用DFS遍历出所有的连通块
3 n个连通块,需要n-1条边来搭建
代码-c++版
#include<cstdio>
#include<vector>
using namespace std;
const int maxn=2000;
vector<int> city[maxn]; //存储与某点相连的边
int v[maxn]; //访问数组
/*初始化访问数组*/
void initial(){
for(int i=0;i<maxn;i++){
v[i]=0;
}
}
/*DFS:深度遍历出每个连通块*/
void DFS(int cur){
v[cur]=1;
for(int i=0;i<city[cur].size();i++){
int child=city[cur][i];
if(v[child]==1) continue;
DFS(child);
}
}
int main(){
int n,m,k; //点数,边数,要去掉的点数
scanf("%d %d %d",&n,&m,&k);
/* 存储点的相连边*/
for(int i=0;i<m;i++){
int in1,in2;
scanf("%d %d",&in1,&in2);
city[in1].push_back(in2);
city[in2].push_back(in1);
}
/* 去掉某点后,检查图中的剩余连通块数*/
for(int j=0;j<k;j++){
int in1;
scanf("%d",&in1);
initial(); //初始化访问数组
v[in1]=1; //去掉该点,因此不用再访问它
/* 用DFS检查剩余的连通块数*/
int b=0; //连通块数
for(int i=1;i<=n;i++){
if(v[i]==1) continue;
DFS(i);
b++;
}
/* 输出需要搭建的边数 */
printf("%d\n",b-1);
}
return 0;
}
代码-python版