链式前向星
2020-09-25 17:12
316 查看
import java.util.Scanner; public class AdjacencyTable { // 节点个数 private int n; // 边的个数 private int m; // 边的编号,从1开始 private int edgeSerial = 0; // lastEdge[i] 保存以 i 为起点的最后一条边的编号 private int[] lastEdge; // 所有的边 private Edge[] edges; static class Edge { // 边的终点 int end; // 边的权重 int weight; // 与该边同起点的上一条边的编号 int previous; public Edge(int end, int weight, int previous) { this.end = end; this.weight = weight; this.previous = previous; } } public AdjacencyTable(int n, int m) { this.n = n; this.m = m; } public void init() { lastEdge = new int[n + 1]; edges = new Edge[m + 1]; } public void add(int a, int b, int weight) { edges[++ edgeSerial] = new Edge(b, weight, lastEdge[a]); lastEdge[a] = edgeSerial; } public void visit(int x) { for (int i = lastEdge[x]; i != 0; i = edges[i].previous) { System.out.println(x + "--->" + edges[i].end + " weight = " + edges[i].weight); } } public void print() { for (int i = 1; i <= n; ++ i) { visit(i); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int m = in.nextInt(); AdjacencyTable table = new AdjacencyTable(n , m); table.init(); while (m -- > 0) { int a = in.nextInt(); int b = in.nextInt(); int weight = in.nextInt(); table.add(a, b, weight); } table.print(); } } }
相关文章推荐
- 边存储结构体:链式前向星
- 链式前向星
- hdu 1874 单源最短路径spfa+链式前向星
- Node:链式前向星
- 链式前向星
- 链式前向星,前向星,vector模拟链表
- -----模板spfa+邻接表,spfa+链式前向星
- 前向星和链式前向星
- 比较重量(华为面试题改)链式前向星的使用+bfs
- 深入理解链式前向星
- 数据结构 链式前向星
- 【最短路模板】floyd dijkstra 链式前向星 + 优先队列 spfa
- 链式前向星
- 图的存储(链式前向星)
- hashtable (vector&链式前向星)
- 好用的链式前向星
- HDU1035 Robot Motion【链式前向星】
- 链式前向星
- 深度理解链式前向星
- 深度理解链式前向星