首页 > 代码库 > 1013. Battle Over Cities (25)(连通分量个数 、 并查集)

1013. Battle Over Cities (25)(连通分量个数 、 并查集)

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 31 21 31 2 3

Sample Output

100

 技术分享

Code:

技术分享
 1 #include <bits/stdc++.h> 2 using namespace std; 3 static const int MAXN = 2e6 + 10; 4 int n , m , k; 5 int data[MAXN][2]; 6 int father[MAXN]; 7 int high[MAXN]; 8  9 void Init()10 {11     for(int i = 0 ; i <= n ; ++i)12     {13         father[i] = i;14         high[i] = 0;15     }16 }17 int FindSet(int x)18 {19     if(x != father[x])20         father[x] = FindSet(father[x]);21     return father[x];22 }23 24 void Unite(int x , int y)25 {26     x = FindSet(x) , y = FindSet(y);27     if(x != y)28     {29         if(high[x] > high[y])30             father[y] = x;31         else32         {33             father[x] = y;34             if(high[x] == high[y])35                 ++high[y];36         }37     }38 }39 int main()40 {41     scanf("%d%d%d" , &n , &m , &k);42 43     for(int i = 1 ; i <= m ; ++i)44         scanf("%d%d" , &data[i][0] , &data[i][1]);45     while(k--)46     {47         int tp;48         Init();49         scanf("%d" , &tp);50         for(int i = 1 ; i <= m ; ++i)51         {52             if(data[i][0] == tp || data[i][1] == tp)53                 continue;54             Unite(data[i][0] , data[i][1]);55         }56         int ans = 0;57         for(int i = 1 ; i <= n ; ++i)58         {59             if(i == tp)60                 continue;61             if(father[i] == i)62                 ++ans;63         }64         if(n != 1)65             printf("%d\n" , ans - 1);66         else67             printf("0");68     }69 }
View Code

 

1013. Battle Over Cities (25)(连通分量个数 、 并查集)