蓝桥杯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_7482336420 分钟前
C++ 模板初阶:从函数重载到泛型编程的优雅过渡
java·c++·算法·1024程序员节
以己之34 分钟前
11.盛最多水的容器
java·算法·双指针·1024程序员节
初级炼丹师(爱说实话版)1 小时前
算法面经常考题整理(3)大模型
算法
Neil今天也要学习2 小时前
永磁同步电机无速度算法--基于相位超前校正的LESO
算法·1024程序员节
码农多耕地呗2 小时前
力扣226.翻转二叉树(java)
算法·leetcode·职场和发展
IT古董4 小时前
【第五章:计算机视觉-项目实战之推荐/广告系统】2.粗排算法-(3)理解粗排模型之在线部分:在线架构及对双塔的应用
算法·1024程序员节
大数据张老师4 小时前
数据结构——平衡二叉树
数据结构·算法·查找
py有趣4 小时前
LeetCode算法学习之合并区间
学习·算法·leetcode
m0_748233644 小时前
单调栈详解【C/C++】
c语言·c++·算法·1024程序员节
郝学胜-神的一滴4 小时前
Linux中的`fork`函数详解:深入解析
linux·服务器·开发语言·c++·算法