蓝桥杯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);
            }
        }
    }
}
相关推荐
XY_墨莲伊13 分钟前
【实战项目】基于B/S结构Flask+Folium技术的出租车轨迹可视化分析系统(文末含完整源代码)
开发语言·后端·python·算法·机器学习·flask
小雅痞23 分钟前
[Java][Leetcode simple] 1. 两数之和
java·算法·leetcode
somi726 分钟前
ARM-驱动-09-LCD FrameBuffer
arm开发·驱动开发·算法·自用
乐迪信息28 分钟前
乐迪信息:智慧港口AI防爆摄像机实现船舶违规靠岸自动抓拍
大数据·人工智能·算法·安全·目标跟踪
winxp-pic31 分钟前
图片校正软件 操作说明及算法介绍
算法
wayz1137 分钟前
Day 6 编程实战:决策树与过拟合分析
算法·决策树·机器学习
ฅ ฅBonnie1 小时前
vLLM 推理后端简介
人工智能·python·算法
贾斯汀玛尔斯1 小时前
每天学一个算法--堆排序(Heap Sort)
数据结构·算法
programhelp_1 小时前
ZipRecruiter CodeSignal OA 2026|最新真题分享 + 速通攻略
数据结构·经验分享·算法·面试
liuyao_xianhui1 小时前
map和set_C++
java·开发语言·数据结构·c++·算法·宽度优先