算法 BISHI95 【模板】链式前向星 思路 求解代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 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(); }