蓝桥杯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);
            }
        }
    }
}
相关推荐
仰泳的熊猫13 小时前
题目1549:蓝桥杯算法提高VIP-盾神与积木游戏
数据结构·c++·算法·蓝桥杯
WW_千谷山4_sch13 小时前
MYOJ_11705:(洛谷P1137)旅行计划(经典拓扑排序)
c++·算法·动态规划·图论
FMRbpm13 小时前
string课后练习
c++·算法·新手入门
BackCatK Chen14 小时前
2026智驾决赛圈:洗牌、技术决战与3大生死门槛
算法·华为·gpu算力·vla·世界模型
王老师青少年编程14 小时前
csp信奥赛C++之摩尔投票算法详解
数据结构·c++·算法·题解·csp·信奥赛·摩尔投票算法
Purple Coder14 小时前
基于GNN的超导材料生长方法研究算法的实现-1
算法
tod11314 小时前
C++ 核心知识点全解析(六)
c++·算法·面试经验
紫陌涵光14 小时前
701. 二叉搜索树中的插入操作
算法·leetcode
tankeven14 小时前
HJ100 等差数列
c++·算法
ADDDDDD_Trouvaille14 小时前
2026.2.22——OJ98-100题
c++·算法