蓝桥杯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);
            }
        }
    }
}
相关推荐
m0_569881474 分钟前
C++中的适配器模式变体
开发语言·c++·算法
NAGNIP16 分钟前
面试官:正则化都有哪些经典的方法?
算法·面试
Theodore_102238 分钟前
深度学习(12)正则化线性回归中的偏差与方差调试
人工智能·深度学习·算法·机器学习·线性回归
m0_569881471 小时前
跨语言调用C++接口
开发语言·c++·算法
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #295:数据流的中位数(双堆法、有序列表、平衡树等多种实现方案详解)
算法·leetcode·优先队列··数据流·中位数·java 面试题
x_xbx1 小时前
LeetCode:215. 数组中的第K个最大元素
数据结构·算法·leetcode
黎阳之光2 小时前
AI数智筑防线 绿色科技启新篇——黎阳之光硬核技术赋能生态安全双升级
大数据·人工智能·算法·安全·数字孪生
2501_924952692 小时前
C++中的过滤器模式
开发语言·c++·算法
萍萍学习2 小时前
蓝桥杯JAVA-3
java·职场和发展·蓝桥杯
2401_873204652 小时前
C++中的组合模式实战
开发语言·c++·算法