蓝桥杯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);
            }
        }
    }
}
相关推荐
槐月杰3 小时前
C语言中冒泡排序和快速排序的区别
c语言·算法·排序算法
笺上山河梦5 小时前
文件操作(二进制文件)
开发语言·c++·学习·算法
大慕慕好懒5 小时前
PHP弱类型hash比较缺陷
算法·哈希算法
snowfoootball6 小时前
最短路问题
数据结构·算法
有你的冬天1987 小时前
数据结构(一)
数据结构·算法
满怀10157 小时前
【Python进阶】列表:全面解析与实战指南
python·算法
爱学习的uu7 小时前
决策树:ID3,C4.5,CART树总结
算法·决策树·机器学习
wuqingshun3141598 小时前
蓝桥杯 9. 九宫幻方
数据结构·c++·算法·职场和发展·蓝桥杯·深度优先
小技与小术8 小时前
代码随想录算法训练营day4(链表)
数据结构·python·算法·链表
yasuniko8 小时前
C复习(主要复习)
c语言·数据结构·算法