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

Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers , 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

Solve

无向图和一些边,让检测当给定点删去后全图是否联通,如果未联通则输出需要新增的边。

该问题可以通过连通分量来解决,对于要检查的点,在搜索连通分量前将其设为已访问,之后枚举所有顶点并dfs访问每个点能最多访问到的点并设状态为已访问,最后进行dfs的次数就是删去要检查的点后的连通分量数。

那么最终讲连通分量看成一个点,将这些点联通所用边最少为 连通分量数-1。

时间复杂度:

  • 建图
  • 每次 DFS ,最多遍历所有城市和边 总共为 ,本题 故可行。

空间复杂度:

  • 图邻接表
  • 状态数组
#include<iostream>
#include<vector>
using namespace std;
 
void dfs(int u, vector<bool> &visited, const int& n, const vector<vector<int>>& graph) {
    visited[u] = true;
    for(int node : graph[u]) {
        if(!visited[node]) {
            dfs(node, visited, n, graph);
        }
    }
}
 
int main() {
    int n, m, k;
    cin >> n >> m >> k;
    vector<vector<int>> graph(n + 1);
    while(m--) {
        int a, b;
        cin >> a >> b;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }
 
    for(int i = 0; i < k;i ++) {
        int node;
        cin >> node;
 
        vector<bool> visited(n+1, false);
        int components = 0;
        visited[node] = true;
        
        for(int j = 1; j <= n; j++) {
            if(!visited[j]) {
                components++;
                dfs(j, visited, n, graph);
            }
        }
 
        cout << components - 1 << endl;
    }
    return 0;
}