题目:
抗日战争时期,冀中平原的地道战曾发挥重要作用。
地道的多个站点间有通道连接,形成了庞大的网络。但也有隐患,当敌人发现了某个站点后,其它站点间可能因此会失去联系。
我们来定义一个危险系数DF(x,y):
对于两个站点x和y (x != y), 如果能找到一个站点z,当z被敌人破坏后,x和y不连通,那么我们称z为关于x,y的关键点。相应的,对于任意一对站点x和y,危险系数DF(x,y)就表示为这两点之间的关键点个数。
本题的任务是:已知网络结构,求两站点之间的危险系数。
输入数据第一行包含2个整数n(2 <= n <= 1000), m(0 <= m <= 2000),分别代表站点数,通道数;
接下来m行,每行两个整数 u,v (1 <= u, v <= n; u != v)代表一条通道;
最后1行,两个数u,v,代表询问两点之间的危险系数DF(u, v)。
使用邻接表存储图,采用深度优先遍历邻接表即可。水题秒过,,,
代码贴上:
import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; public class Main { static int nodeCount; static int edgeCount; static Node[] nodeArray; static int begin; static int end; static int count = 0; static boolean[] juge; static class Node { HashSet<Integer> set = new HashSet<Integer>(); public void addEdge(int num) { this.set.add(num); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); nodeCount = sc.nextInt(); edgeCount = sc.nextInt(); nodeArray = new Node[nodeCount + 1]; for (int i = 0; i <= nodeCount; i++) { nodeArray[i] = new Node(); } for (int i = 0; i < edgeCount; i++) { int one = sc.nextInt(); int two = sc.nextInt(); nodeArray[one].addEdge(two); nodeArray[two].addEdge(one); } begin = sc.nextInt(); end = sc.nextInt(); sc.close(); juge = new boolean[nodeCount + 1]; juge[begin] = true; if (check(begin) == -1) { System.out.println(-1); return; } for (int i = 1; i <= nodeCount; i++) { juge = new boolean[nodeCount + 1]; juge[begin] = juge[i] = true; if (i != begin && i != end) { count = check(begin) != 0 ? count + 1 : count; } } System.out.println(count); } private static int check(int start) { HashSet<Integer> s = nodeArray[start].set; Iterator<Integer> it = s.iterator(); while (it.hasNext()) { int num = it.next(); if (num == end) { return 0; } if (!juge[num]) { juge[num] = true; if (check(num) == 0) { return 0; } juge[num] = false; } } return -1; } }
原文地址:http://blog.csdn.net/u011333588/article/details/46003361