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 (<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 import java.util.Arrays; 2 import java.util.Scanner; 3 4 /** 5 * @Auther: Xingzheng Wang 6 * @Date: 2019/2/20 16:50 7 * @Description: pattest 8 * @Version: 1.0 9 */ 10 public class PAT1013 { 11 12 static int[][] map = new int[1001][1001]; 13 static boolean[] visit = new boolean[1001]; 14 static int n = 0; 15 16 //DFS 17 static public void dfs(int start) { 18 visit[start] = true; 19 for (int i = 1; i <= n; i++) { 20 if (visit[i] == false && map[start][i] == 1) 21 dfs(i); 22 } 23 } 24 25 public static void main(String[] args) { 26 Scanner cin = new Scanner(System.in); 27 int i; 28 n = cin.nextInt(); 29 int m = cin.nextInt(); 30 int k = cin.nextInt(); 31 for (i = 0; i < m; i++) { 32 int x = cin.nextInt(); 33 int y = cin.nextInt(); 34 map[x][y] = map[y][x] = 1; 35 } 36 for (int s = 0; s < k; s++) { 37 int cnt = 0; 38 Arrays.fill(visit, false); //填充每个visit数组都是 false; 39 int temp = cin.nextInt(); 40 visit[temp] = true; 41 for (i = 1; i <= n; i++) { 42 if (visit[i] == false) { 43 dfs(i); 44 cnt++; 45 } 46 } 47 System.out.println(cnt - 1); 48 } 49 } 50 }
本文介绍了一种算法,用于解决战争中城市被占领后,为保持剩余城市间连接而需快速判断并修复哪些高速公路的问题。通过输入剩余的高速公路信息和关注的城市列表,算法能够迅速计算出若某城市被占领,需要修复的高速公路数量。
Java&spm=1001.2101.3001.5002&articleId=101581061&d=1&t=3&u=6d45b626579d48858bdae69959e7b499)
339

被折叠的 条评论
为什么被折叠?



