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 Input3 2 3 1 2 1 3 1 2 3Sample Output
1 00
这题是使用并查集过的,思路是先将所有的城市之间的路径先保存下来。然后查询每个城市的时候,将有关这个城市的路线都不加入,每次形成一个新的并查集,查询联通分支数。需要注意的是,在计算联通分支数的时候,要将查询的城市这个点去除,不然会影响结果。一开始想到这个思路的时候,觉得不太可能,每次都要重新生成一遍并查集过,应该会很慢吧,但是想不到其他的想法,于是就尝试了一下,没想到真的过了。
#include<iostream> #include<stdio.h> #include<string.h> #include<vector> using namespace std; int father[1005]; int flag[1005]; void init(){ memset(flag,0,sizeof(flag)); for(int i = 0;i < 1005;i++){ father[i] = i; } } //压缩路径 int getfather(int x){ if(x != father[x]){ father[x] = getfather(father[x]); } return father[x]; } void join(int x,int y){ int i = getfather(x); int j = getfather(y); if(i != j){ father[i] = j; } } struct way{ int x,y; }; int main(){ for(int n,m,k;scanf("%d%d%d",&n,&m,&k)!= EOF;){ //将城市之间的路径保存下来 vector<way>ways; for(int i = 0;i < m;i++){ way temp; scanf("%d%d",&temp.x,&temp.y); ways.push_back(temp); } for(int i = 0;i < k;i++){ int q; scanf("%d",&q); //对于每次城市的查询。重新生成一个新的并查集 init(); for(int j = 0;j < ways.size();j++){ if(ways[j].x != q && ways[j].y != q){ join(ways[j].x,ways[j].y); } } for(int j = 1;j <= n;j++){ flag[getfather(j)] = 1; } int count = 0; for(int j = 1;j <= n;j++){ //考虑查询城市这个点,这个点应该是要被去掉的 if(j == q){ continue; } if(flag[j]){ count++; } } printf("%d\n",count-1); } } return 0; }