蓝桥杯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);
            }
        }
    }
}
相关推荐
叼烟扛炮19 分钟前
C++ 知识点18 内部类
开发语言·c++·算法·内部类
YOGOD有神19 分钟前
用AI自动从谷歌地图抓取海外客户,我跑了一次7小时的任务,结果出乎意料
算法
汉克老师23 分钟前
GESP5级C++考试语法知识(十五、分治算法(二))
c++·算法·排序算法·分治算法·gesp5级·gesp五级
快瞳科技24 分钟前
小样本学习在珍稀鸟类识别中的突破:仅需5张图,让AI认识濒危物种
算法
汉克老师43 分钟前
GESP6级C++考试语法知识(五、格雷码)
c++·算法·位运算·异或·gesp6级·gesp六级·格雷码
Ulyanov1 小时前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 可视化革命——基于 PyVista 的 3D 战场构建与实时渲染
开发语言·python·算法·3d·系统仿真
,,?!,1 小时前
数据结构算法-排序算法
数据结构·算法·排序算法
小白编程锤炼1 小时前
深入解析:质量门禁
人工智能·算法·架构·vibe-coding
yongui478342 小时前
基于 GA 优化的 BP 神经网络算法分析与 MATLAB 实现
神经网络·算法·matlab
阿旭超级学得完3 小时前
C++11(初始化)
java·开发语言·数据结构·c++·算法