蓝桥杯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);
            }
        }
    }
}
相关推荐
其实防守也摸鱼5 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
Nuanyt5 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
w_zero_one9 小时前
递归算法(一)
java·开发语言·算法
风影同志7832410 小时前
20 个比特能装下多少行情?——实测拆解 Kronos 的 K 线分词器
算法
写的都是BUG11 小时前
APK 里的钥匙,一直就放在门口:聊聊加固真正该做什么
前端·算法
地平线开发者11 小时前
CLIP 的零样本分类:一组文本如何变成图像分类器?
算法
京东云开发者12 小时前
从“会生成”到“能生产”:萤火虫 AIGC 平台的 AI Infra 实践
算法·aigc·产品
youshi666812 小时前
PID——算法改进
算法
一只不想敲代码的程序猿13 小时前
如何更高效地拆解问题?
算法