蓝桥杯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);
            }
        }
    }
}
相关推荐
_Itachi__33 分钟前
LeetCode 热题 100 543. 二叉树的直径
java·算法·leetcode
是代码侠呀1 小时前
飞蛾扑火算法matlab实现
开发语言·算法·matlab·github·github star·github 加星
C++ 老炮儿的技术栈2 小时前
C++中什么是函数指针?
c语言·c++·笔记·学习·算法
大耳猫3 小时前
卡尔曼滤波算法简介与 Kotlin 实现
算法·kotlin·卡尔曼滤波
重生之后端学习3 小时前
day23-集合(泛型&Set&数据结构)
java·开发语言·数据结构·算法
焜昱错眩..4 小时前
代码随想录训练营第二十一天 |589.N叉数的前序遍历 590.N叉树的后序遍历
数据结构·算法
Tisfy4 小时前
LeetCode 1550.存在连续三个奇数的数组:遍历
算法·leetcode·题解·数组·遍历
wang__123004 小时前
力扣70题解
算法·leetcode·职场和发展
咚咚轩4 小时前
蓝桥杯14届 数三角
蓝桥杯·stl
菜鸟破茧计划4 小时前
滑动窗口:穿越数据的时光机
java·数据结构·算法