蓝桥杯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);
            }
        }
    }
}
相关推荐
北顾笙98013 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_6294947313 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai13 小时前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
旖-旎13 小时前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
@小码农13 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
Wect14 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·算法·typescript
糖果店的幽灵14 小时前
决策树详解与sklearn实战
算法·决策树·sklearn
Lewiis14 小时前
趣谈排序算法
算法·排序算法
ComputerInBook14 小时前
数字图像处理(4版)——第 8 章——图像压缩与水印(上)(Rafael C.Gonzalez&Richard E. Woods)
人工智能·算法·计算机视觉·图像压缩·图像水印
刀法如飞14 小时前
Python列表去重:从新手三连到高阶特技,20种解法全收录
python·算法·编程语言