PAT 1013 Battle Over Cities
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 city 1 -city 2 and city 1 -city 3 . Then if city 1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city 2 -city 3 .
Input Specification:
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 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 #include <iostream> 2 #include <stdio.h> 3 4 5 using namespace std; 6 7 struct Edge 8 { 9 int a; 10 int b; 11 }edge[1100000]; 12 13 int Tree[1100]; 14 15 int findRoot(int x) 16 { 17 if(Tree[x] == -1) 18 return x; 19 int tmp = findRoot(Tree[x]); 20 Tree[x] = tmp; 21 return tmp; 22 } 23 24 25 int main() 26 { 27 int n, m, k; 28 scanf("%d%d%d", &n, &m, &k); 29 30 for(int i = 0; i < m; ++i) 31 scanf("%d%d", &edge[i].a, &edge[i].b); 32 33 int t; 34 for(int x = 1; x <= k; ++x) 35 { 36 scanf("%d", &t); 37 38 // 初始化并查集 39 for(int i = 1; i <= n; ++i) 40 Tree[i] = -1; 41 42 // 遍历所有边,建立并查集 43 for(int i = 0; i < m; ++i) 44 { 45 if(edge[i].a == t || edge[i].b == t) 46 continue; 47 48 int ra = findRoot(edge[i].a); 49 int rb = findRoot(edge[i].b); 50 // 合并 51 if(ra != rb) 52 Tree[ra] = rb; 53 } 54 55 int cnt = 0; //并查集中集合的个数 56 for(int i = 1; i <=n ;++i) 57 { 58 if(Tree[i] == -1) 59 cnt++; 60 } 61 62 if(x == k) 63 cout << cnt-2; 64 else 65 cout << cnt-2 << endl; 66 } 67 68 69 return 0; 70 }