蓝桥杯15届JavaB组6题

一开始用的dfs,但是好像是因为数据量太大,数据错误,而且会超时,然后使用bfs

dfs的代码(自留):

java 复制代码
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);
            }
        }
    }
}
相关推荐
Once_day5 分钟前
代码训练LeetCode(21)跳跃游戏2
算法·leetcode
德先生&赛先生1 小时前
LeetCode-934. 最短的桥
算法·leetcode·职场和发展
CCF_NOI.2 小时前
洛谷P12610 ——[CCC 2025 Junior] Donut Shop
算法
鑫鑫向栄3 小时前
[蓝桥杯]模型染色
数据结构·c++·算法·职场和发展·蓝桥杯
1白天的黑夜14 小时前
栈-20.有效的括号-力扣(LeetCode)
c++·算法·leetcode
小白程序员丶钟同学4 小时前
L1-019 谁先倒 (15 分)
数据结构·算法
<但凡.5 小时前
题海拾贝:P2347 [NOIP 1996 提高组] 砝码称重
数据结构·c++·算法
bubiyoushang8885 小时前
matlab实现高斯烟羽模型算法
开发语言·算法·matlab