蓝桥杯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 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
墨韵流芳5 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
csdn_aspnet6 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
凌波粒6 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
2301_800895106 小时前
洛谷蓝桥杯模拟赛--备战蓝桥杯版
蓝桥杯
我叫洋洋7 小时前
[Proteus 和 stm32f103c8t6]的使用控制OLED篇]
c语言·stm32·单片机·嵌入式硬件·蓝桥杯·proteus
paeamecium8 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
Book思议-8 小时前
【数据结构】栈与队列全方位对比 + C 语言完整实现
c语言·数据结构·算法··队列
SteveSenna8 小时前
项目:Trossen Arm MuJoCo
人工智能·学习·算法
NAGNIP8 小时前
一文搞懂CNN经典架构-DenseNet!
算法·面试