蓝桥杯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);
            }
        }
    }
}
相关推荐
广州灵眸科技有限公司7 分钟前
瑞芯微(EASY EAI)RV1126B rknn-toolkit-lite2使用方法
linux·网络·人工智能·物联网·算法
旖-旎22 分钟前
深搜(二叉树剪枝)(3)
数据结构·c++·算法·力扣·剪枝·递归
流年如夢24 分钟前
结构体:定义、使用与内存布局
c语言·开发语言·数据结构·c++·算法
『昊纸』℃1 小时前
C语言学习心得集合 篇1
c语言·算法·编程基础·学习心得·实践操作
Chase_______1 小时前
LeetCode 1456:定长子串中元音的最大数目
算法·leetcode
小O的算法实验室1 小时前
2026年IEEE IOTJ,DNA序列启发相似性驱动粒子群算法+无人机与基站部署,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
谭欣辰1 小时前
Floyd算法:动态规划解最短路径
c++·算法·图论
计算机安禾1 小时前
【Linux从入门到精通】第12篇:进程的前后台切换与信号控制
linux·运维·算法
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 84. 柱状图中最大的矩形 | C++ 两次单调栈基础扫法
c++·算法·leetcode
C雨后彩虹1 小时前
文件目录大小
java·数据结构·算法·华为·面试