蓝桥杯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);
            }
        }
    }
}
相关推荐
程序员-King.3 分钟前
day115—同向双指针—将x减到0的最小操作数(LeetCode-1658)
算法·leetcode·双指针
全栈工程师修炼指南4 分钟前
Nginx | 负载均衡策略:一致性哈希算法实践
运维·算法·nginx·负载均衡·哈希算法
Jerryhut10 分钟前
sklearn函数总结六——特征降维 压缩数据 - 特征提取(PCA&LDA)
人工智能·算法·机器学习·scikit-learn·sklearn
apcipot_rain21 分钟前
CCF算法能力大赛T3 暴力法 反思
算法
前端小白在前进33 分钟前
力扣刷题:有效的括号
算法·leetcode·职场和发展
EXtreme3536 分钟前
算法深潜:链表中的生死之环(LeetCode 141 & 142 详解)
数据结构·算法·leetcode·链表·快慢指针·数学证明·带环链表
2301_8035545241 分钟前
Pimpl(Pointer to Implementation)设计模式详解
c++·算法·设计模式
leoufung1 小时前
LeetCode 211:设计添加与搜索单词的数据结构(Trie + DFS)
数据结构·leetcode·深度优先
资深web全栈开发1 小时前
LeetCode 3578:统计极差最大为 K 的分割方式数 - 深入浅出指南
算法·leetcode·前缀和·动态规划·滑动窗口
不会c嘎嘎1 小时前
算法百练 ,直击OFFER -- DAY7
算法