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:
3 2 3
1 2
1 3
1 2 3
Sample Output:
1
0
0
这道题题目一开始也看不懂(我太菜了),这道题是给你几个顶点和几条连接顶点的边,让你分别求如果少了某个结点,需要再修几条路才能把剩余的结点变为连通图。
只要知道一点这道题就比较好做了,n个连通块(连通分量)需要n-1条边来连接。
所以这道题要做的就是求出连通分量(连通块)的个数,这里采用的是dfs,设置一个vis数组。每遍历一个结点时,把cnt重置为0,马上把这个结点的vis设为true,因为这个点是被删除状态的,只要被设为已访问,那么它和它的边将不会被访问。
因为序号是从1-N的,所以从1重新开始遍历所有结点,因为要删除的结点已经被标记已访问了所以不用担心。如果当前遍历的结点未被访问,就dfs这个点,dfs里面将当前结点设为已访问,并遍历当前结点的连通结点也就是两点之间距离为1,且当前结点未被遍历,就把当前结点设为已访问,并dfs这个结点的联通结点。如果这个连通块遍历完了,自然而然就退出dfs了,那么cnt++,cnt就是连通块的数量。
最后遍历完后输出cnt-1
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int MAXV = 1010;
const int INF = 1000000000;
int G[MAXV][MAXV], n;
bool vis[MAXV];
void dfs(int node){
vis[node] = true;
for(int i = 1; i <= n; i++){
if(G[node][i] == 1 && vis[i] == false){
vis[i] = true;
dfs(i);
}
}
}
int main(){
int m, k;
int u, v;
fill(G[0], G[0] + MAXV * MAXV, INF);
scanf("%d %d %d", &n, &m, &k);
for(int i = 0; i < m; i++){
scanf("%d %d", &u, &v);
G[u][v] = G[v][u] = 1;
}
for(int i = 0; i < k; i++){
fill(vis, vis + MAXV, false);
scanf("%d", &u);
int cnt = 0;
vis[u] = true;
for(int j = 1; j <= n; j++){
if(vis[j] == false){
dfs(j);
cnt++;
}
}
printf("%d\n",cnt-1);
}
return 0;
}