蓝桥杯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);
            }
        }
    }
}
相关推荐
清木铎38 分钟前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎41 分钟前
leetcode_day10_筑基期_《绝境求生》
算法
j_jiajia1 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
源代码•宸1 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
Jasmine_llq3 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计
小棠师姐3 小时前
支持向量机(SVM)入门:超平面与核函数的通俗解释
算法·python机器学习·支持向量机svm·超平面可视化·核函数应用
im_AMBER3 小时前
Leetcode 102 反转链表
数据结构·c++·学习·算法·leetcode·链表
今儿敲了吗4 小时前
01|多项式输出
c++·笔记·算法
Xの哲學4 小时前
深入剖析Linux文件系统数据结构实现机制
linux·运维·网络·数据结构·算法
AlenTech4 小时前
200. 岛屿数量 - 力扣(LeetCode)
算法·leetcode·职场和发展