蓝桥杯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);
            }
        }
    }
}
相关推荐
_深海凉_5 分钟前
LeetCode热题100-杨辉三角
算法·leetcode·职场和发展
小O的算法实验室16 分钟前
2025年SEVC,面向进化计算的学习注入式优化,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
啊我不会诶25 分钟前
2024北京市赛补题
c++·算法
shehuiyuelaiyuehao25 分钟前
算法13,滑动窗口,水果成篮
算法·哈希算法·散列表
智慧物业老杨26 分钟前
物业数智化转型实战:从单一服务到综合解决方案的技术落地路径
人工智能·算法·ai
夏末蝉未鸣0129 分钟前
Sort-Merge Join【排序连接算法】详解(python代码实现,以FULL JOIN为例)
数据结构·算法
tjl521314_2136 分钟前
01C++ 分离编译与多文件编程
前端·c++·算法
_日拱一卒37 分钟前
LeetCode:23合并K个升序链表
java·数据结构·算法·leetcode·链表·职场和发展
哆啦刘小洋40 分钟前
【LeetCode每日一题】:2033(贪心+快速排序魔改)
算法·leetcode
WolfGang00732143 分钟前
代码随想录算法训练营 Day48 | 图论 part06
算法·图论