蓝桥杯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);
            }
        }
    }
}
相关推荐
CQU_JIAKE7 分钟前
【A】3742,3387,并查集
算法
gihigo19989 分钟前
CHAN时延估计算法(二维/三维定位实现)
算法
freexyn29 分钟前
Matlab自学笔记七十六:表达式的展开、因式分解、化简、合并同类项
笔记·算法·matlab
样例过了就是过了32 分钟前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
dog2501 小时前
圆锥曲线和二次曲线
开发语言·网络·人工智能·算法·php
Wadli1 小时前
27.单调队列
算法
Navigator_Z1 小时前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
Wect1 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·typescript
爱学习的张大2 小时前
具身智能论文问答(三):Open VLA
人工智能·算法
wearegogog1232 小时前
基于Q-learning的栅格地图路径规划MATLAB仿真程序
开发语言·算法·matlab