一开始用的dfs,但是好像是因为数据量太大,数据错误,而且会超时,然后使用bfs
dfs的代码(自留):
import java.util.*;public class F15 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int m = sc.nextInt();int q = sc.nextInt();int result = 0;int[][] g = new int[n + 1][n + 1];for (int i = 0; i < m; i++) {int a = sc.nextInt();int b = sc.nextInt();g[a][b] = 1;g[b][a] = 1;}for (int i = 0; i < q; i++) {boolean[] dest = new boolean[n + 1];dest[0] = true;int start = sc.nextInt();int count = sc.nextInt();dfs(start, g, count, dest);for (int j = 1; j < dest.length; j++) {if (dest[j] == true) {result++;}}}double x = (double) result / q;System.out.printf("%.2f", x);}public static void dfs(int start, int[][] g, int count, boolean[] dest) {dest[start] = true;if (count == 0) return;for (int i = 1; i < g.length; i++) {if (i == start) continue;if (g[start][i] == 1 && dest[i] == false) {count--;dfs(i, g, count, dest);}}}
}