蓝桥杯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);
            }
        }
    }
}
相关推荐
发发就是发16 分钟前
USB系统架构概述:从一次诡异的枚举失败说起
驱动开发·单片机·嵌入式硬件·算法·fpga开发
少许极端18 分钟前
算法奇妙屋(四十七)-ST表
算法·st表·rmq
kishu_iOS&AI36 分钟前
Pytorch —— 自动微分模块
人工智能·pytorch·python·深度学习·算法·线性回归
北风toto1 小时前
深入解析JWT Token生成原理与安全加密技术详解
算法·安全·哈希算法
DeepModel1 小时前
通俗易懂讲透 EM 算法(期望最大化)
人工智能·python·算法·机器学习
Pentane.1 小时前
【力扣hot100】【Leetcode 15】三数之和|暴力枚举 双指针 算法笔记及打卡(14/100)
数据结构·笔记·算法·leetcode
不知名的老吴1 小时前
高阶函数的应用与函数对象概念
算法
Mr_pyx1 小时前
【LeetCode Hot 100】 - 缺失的第一个正数完全题解
数据结构·算法
wydxry1 小时前
深入解析自适应光学中的哈特曼波前传感技术:原理、算法与智能化前沿
大数据·人工智能·算法
xieliyu.1 小时前
Java顺序表实现扑克牌Fisher-Yates 洗牌算法
java·数据结构·算法·javase