蓝桥杯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);
            }
        }
    }
}
相关推荐
云析赢指标公式网437 分钟前
文华WH6布林轨道均线强弱共振指标公式
前端·算法
luj_17681 小时前
一线一区一变破解人盯人防守密码
开发语言·网络·c++·经验分享·算法
Wang's Blog1 小时前
Java框架快速入门: Spring Security+OAuth2之字段验证与自定义验证注解实战
java·算法·spring
带多刺的玫瑰1 小时前
Leecode#29刷题之两数相除
java·python·算法
smj2302_796826522 小时前
解决leetcode第4017题数组中的峰值II
python·算法·leetcode
午彦琳2 小时前
2026.9.9
数据结构·算法·leetcode
luj_17682 小时前
中锋卡位与开放线博弈
c语言·开发语言·网络·经验分享·算法
洋不写bug2 小时前
二叉树(四)经典算法题目解析,公共祖先,二叉树构造,非递归遍历
数据库·算法·二叉树·二叉树构造·公共祖先
hansang_IR2 小时前
【题解】P4454 [CQOI2018] 破解D-H协议
c++·算法·密码学·数论
梓䈑2 小时前
【动态规划系列】路径问题、子数组 和 子序列问题、背包问题
c++·算法·动态规划