题解 | 【模板】链式前向星

【模板】链式前向星

https://www.nowcoder.com/practice/23f622c8b15f4b37bffe1a986eeea185

import java.io.*;
import java.util.*;

public class Main {
      public static void main(String[] args) throws IOException {
        // 使用BufferedReader读取输入,PrintWriter输出结果
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

        // 读取第一行输入,分割字符串并转换为整数n和m
        String[] strA = br.readLine().trim().split("\\s+");
        int n = Integer.parseInt(strA[0]);  // 节点数
        int m = Integer.parseInt(strA[1]);  // 边数

        // 创建邻接表,大小为n+1(节点从1开始编号)
        List<Integer>[] adj = new ArrayList[n + 1];
        // 初始化每个节点的邻接表
        for (int i = 1; i <= n; i++) {
            adj[i] = new ArrayList<>();
        }

        // 读取m条边,构建无向图的邻接表
        for (int i = 0; i < m; i++) {

            // 读取边的两个端点
            String[] edge = br.readLine().trim().split("\\s+");
            int u = Integer.parseInt(edge[0]);  // 边的一个端点
            int v = Integer.parseInt(edge[1]);  // 边的另一个端点
            // 无向图,两个方向都添加
            adj[u].add(v);
            adj[v].add(u);
        }

        // 遍历每个节点,输出其邻接节点
        for (int i = 1; i <= n; i++) {
            // 如果节点没有邻接节点,输出"None"
            if (adj[i].isEmpty()) {
                out.println("None");
            } else {
                // 对邻接节点进行排序
                Collections.sort(adj[i]);

                // 输出排序后的邻接节点
                for (int j = 0; j < adj[i].size(); j++) {
                    // 如果是最后一个节点,直接输出,否则输出空格
                    out.print(adj[i].get(j) + (j == adj[i].size() - 1 ? "" : " "));
                }
                out.println();
            }
        }


        // 刷新缓冲区并释放资源
        out.flush();
        out.close();
        br.close();
    }


}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务