A1013. 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
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
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<iostream> 3 #include<vector> 4 #include<queue> 5 using namespace std; 6 int G[1001][1001] = {0}; 7 int visit[1001] = {0}, cnt = 0; 8 int N, M, K; 9 void dfs(int vt, int lost){ 10 visit[vt] = 1; 11 for(int i = 1; i <= N; i++){ 12 if(G[vt][i] == 1 && visit[i] == 0 && i != lost && vt != lost){ 13 dfs(i, lost); 14 } 15 } 16 } 17 int main(){ 18 scanf("%d%d%d", &N, &M, &K); 19 int tempA, tempB; 20 for(int i = 0; i < M; i++){ 21 scanf("%d%d", &tempA, &tempB); 22 G[tempA][tempB] = G[tempB][tempA] = 1; 23 } 24 for(int i = 0; i < K; i++){ 25 int lost; 26 scanf("%d", &lost); 27 for(int j = 1; j <= N; j++) 28 visit[j] = 0; 29 visit[lost] = 1; 30 cnt = 0; 31 for(int j = 1; j <= N; j++){ 32 if(visit[j] == 0){ 33 dfs(j, lost); 34 cnt++; 35 } 36 } 37 printf("%d\n", cnt - 1); 38 } 39 cin >> N; 40 return 0; 41 }
总结:
1、题意:给出一个无向图G,再给出一个要去掉的节点,求图G在去掉该节点之后的连通分量个数。
2、要去掉lost的点,但在图G上直接将它与所有的点的边置0是不行的,因为不止一个查询,置0后无法恢复。可以在dfs传入lost的点,遍历的时候避开该点即可。
3、计数连通分量个数:利用visit数组,由于一次从点A开始的搜索会把所有和A联通的节点置1。所以可以从1到N每个节点使用一次dfs,当它的visit为0时,说明它和之前访问的节点不属于同一个连通分量。
4、还可以使用并查集:在输入每条边时,判断边上的两个点是否在同一个集合,如果在则不做改变,如果不在,则对两个集合做并。需要路径压缩。