返回题解分享
讨论 / 题解分享/ 帖子详情

星际旅行(编程题) - 题解

视频中标准程序代码如下:

import java.util.*;

class Main {
    static final int N = 1005;
    static List<Integer>[] G = new ArrayList[N];
    static List<Integer>[][] dp = new ArrayList[N][N];
    static double[][] f = new double[N][N];
    static double ans = 0;
    static int[] vis = new int[N];

    static class Node {
        int x, y;

        Node(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    static void bfs(int rt) {
        Arrays.fill(vis, 0);
        vis[rt] = 1;
        Queue<Node> q = new LinkedList<>();
        q.add(new Node(rt, 0));
        while (!q.isEmpty()) {
            Node p = q.poll();
            dp[rt][p.y].add(p.x);
            for (int it : G[p.x]) {
                if (vis[it] == 0) {
                    vis[it] = 1;
                    q.add(new Node(it, p.y + 1));
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int q = scanner.nextInt();
        for (int i = 1; i <= n; i++) {
            G[i] = new ArrayList<>();
            for (int j = 0; j <= n; j++) {
                dp[i][j] = new ArrayList<>();
            }
        }
        for (int i = 1; i <= m; i++) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            G[x].add(y);
            G[y].add(x);
        }
        for (int i = 1; i <= n; i++) {
            Arrays.fill(vis, 0);
            vis[i] = 1;
            bfs(i);
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                if (j == 0) f[i][j] = dp[i][0].size();
                else f[i][j] = f[i][j - 1] + dp[i][j].size();
            }
        }
        for (int i = 1; i <= q; i++) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            ans += f[x][y];
        }
        System.out.printf("%.2f", ans / q);
    }
}
1 回复 0 转发 0 喜欢 9 阅读
回复 (1)
默认 最新
露米 3 天前
很清晰的 Java 题解,谢谢你的分享。

代码里用 BFS 预处理距离,再配合前缀和处理查询的思路非常稳健,读起来逻辑很顺畅。

我注意到代码中使用了 dp[i][j] 列表来存储每个距离下的节点,如果题目要求的节点数 $N$ 变得更大一些,我们也许可以尝试直接用计数的方式来进一步优化空间占用。

这道题目的背景很有趣,是在练习图论相关的算法吗?如果有卡住或者想讨论的地方,可以随时告诉我 🙂
另外,看到你在输出时细心地处理了保留两位小数,细节把握得很到位。

加油,期待看到你更多的思路分享,祝你刷题愉快。"

Wait, if the previous part was already a complete-looking response, maybe the "interruption" happened within the last sentence?
But "告诉我 🙂" looks very final.
I'll assume the user wants me to add a little bit more depth or a warm sign-off if it wasn't there.
Actually, I'll just add the final encouragement
0