2014
01-13

# 九度-1325-Battle Over Cities[并查集]

### 题目1325：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.

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.

For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

3 2 3
1 2
1 3
1 2 3

1
0
0

1、存储最原先的数据。
2、在循环k个城市的时候，判断a和b都不被控制，那么就把二者

3、求并查集的个数。总的集合的个数减去1就是需要修的路。

Java代码如下：

 //author:wzqwsrf
import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.HashSet;
import java.util.Set;

public class Main {
/*
* 1325
*/
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
while (st.nextToken() != StreamTokenizer.TT_EOF) {
int n = (int)st.nval;
st.nextToken();
int m = (int)st.nval;
st.nextToken();
int k = (int)st.nval;
int connectArr[][] = new int[m][2];
for (int i = 0; i < m; i++) {
int array[] = new int[2];
st.nextToken();
array[0] = (int)st.nval;
st.nextToken();
array[1] = (int)st.nval;
connectArr[i] = array;
}

int[] parent = new int[n + 1];

for (int i = 0; i < k; i++) {
for (int j = 1; j <= n; j++) {
parent[j] = j;
}
st.nextToken();
int city = (int)st.nval;
for (int j = 0; j < m; j++) {
int array[] = connectArr[j];
if (array[0] != city && array[1] != city) {
union(array[0], array[1], parent);
}
}

for (int j = 1; j < n + 1; j++) {
parent[j] = findParent(j, parent);
}
Set<Integer> numSet = new HashSet<Integer>();
for (int j = 1; j < n + 1; j++) {
}
System.out.println(numSet.size() - 2);
}

}
}

private static void union(int f, int t, int[] parent) {

int a = findParent(f, parent);
int b = findParent(t, parent);
if (a == b)
return;
if (a > b) {
parent[a] = b;
} else {
parent[b] = a;
}
}

private static int findParent(int f, int[] parent) {
while (parent[f] != f) {
f = parent[f];
}
return f;
}
}

1. “”转基因的害处目前无从判定，就算会让人得病，降低人口平均年龄虽说不是什么好事，但反而有助于减轻中国目前的人口压力。政府在缺粮动荡和人口平均年龄降低之间只能两害取其轻，永远不要忘记政治的黑暗性，牺牲一部分人的健康来保持国家长久稳定听上去是不那么光彩，但很有