题目:
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 (<), Mand 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 #include2 #include 3 using namespace std; 4 vector<int> map[1001]; 5 int par[1001]; 6 int n,m,k; 7 int close; //攻陷的城市(不能连接的结点) 8 9 void init(){ //初始化,每一个结点的父亲结点是该点自己 10 for(int i=1;i<=n;i++){ 11 par[i]=i; 12 } 13 } 14 15 int find(int x){ //寻找父亲结点 16 if(par[x]==x){ 17 return x; 18 }else{ 19 return find(par[x]); 20 } 21 } 22 23 void unit(int x,int y){ //合并两个分块 24 x=find(x); 25 y=find(y); 26 if(x!=y){ 27 par[x]=y; 28 } 29 } 30 31 int main(){ 32 cin>>n>>m>>k; 33 int u,v; 34 for(int i=0;i ){ 35 cin>>u>>v; 36 map[u].push_back(v); //路径是双向的 37 map[v].push_back(u); 38 } 39 for(int i=0;i ){ 40 init(); 41 cin>>close; 42 for(int i=1;i<=n;i++){ 43 for(vector<int>::iterator it=map[i].begin();it!=map[i].end();it++){ 44 if(i!=close&&*it!=close){ 45 unit(i,*it); 46 } 47 } 48 } 49 int ans=0; 50 for(int i=1;i<=n;i++){ //查找分块的数量 51 if(find(i)==i&&i!=close){ 52 ans++; 53 } 54 } 55 cout< 1<<endl; 56 } 57 return 0; 58 }