蓝桥杯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);
            }
        }
    }
}
相关推荐
50万马克的面包10 小时前
C语言:三大基础排序算法模板 冒泡 / 选择 / 插入)
c语言·笔记·算法·排序算法
罗超驿10 小时前
3.快乐数专题学习笔记——双指针法在LeetCode 202题中的应用
java·算法·leetcode·职场和发展
无限进步_10 小时前
【C++】深入底层:自己动手实现一个哈希表
开发语言·数据结构·c++·算法·链表·散列表·visual studio
_深海凉_10 小时前
LeetCode热题100-小于 n 的最大数(字节高频题)
算法·leetcode·职场和发展
小雅痞10 小时前
[Java][Leetcode middle] 36. 有效的数独
java·算法·leetcode
paeamecium10 小时前
【PAT甲级真题】- General Palindromic Number(20)
数据结构·c++·算法·pat考试·pat
北顾笙98010 小时前
day43-数据结构力扣
数据结构·算法·leetcode
sali-tec10 小时前
C# 基于OpenCv的视觉工作流-章69-圆弧测量
图像处理·人工智能·opencv·算法·计算机视觉
AI科技星10 小时前
圓 全域数学·72分册·哈希原本卷(七册分卷 · 72分册 · 习题与猜想版)
人工智能·算法·数学建模·数据挖掘·哈希算法·量子计算
sali-tec10 小时前
C# 基于OpenCv的视觉工作流-章70-轮廓点距
图像处理·人工智能·opencv·算法·计算机视觉