蓝桥杯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);
            }
        }
    }
}
相关推荐
Swift社区1 分钟前
LeetCode 452 - 用最少数量的箭引爆气球
算法·leetcode·职场和发展
mjhcsp14 分钟前
题解:P8727 [蓝桥杯 2020 国 A] 填空问题
算法
Lucis__15 分钟前
红黑树实现—规则&约束的平衡之道
数据结构·c++·算法·红黑树
yaoh.wang18 分钟前
力扣(LeetCode) 70: 爬楼梯 - 解法思路
python·算法·leetcode·面试·职场和发展·动态规划·递归
逸风尊者26 分钟前
开发可掌握的知识:推荐系统
java·后端·算法
Learner__Q30 分钟前
每天五分钟:二分查找-LeetCode高频题解析_day4
python·算法·leetcode
智者知已应修善业33 分钟前
【字符串提取3个整数求和】2024-2-11
c语言·c++·经验分享·笔记·算法
唯唯qwe-37 分钟前
Day21:贪心算法 | 加油站,分发糖果
算法·贪心算法
点云侠1 小时前
粒子群优化算法求解三维变换矩阵的数学推导
线性代数·算法·矩阵
dragoooon341 小时前
[hot100 NO.31~36]
数据结构·算法·排序算法