用邻接表表示带权有向图
/* 用邻接表表示带权有向图 */ import java.util.ArrayList; import java.util.Scanner; public class Test { //图的顶点数,总边数 static int V, E; //存储所有的边,大小为顶点数 static ArrayList<Edge>[] Edges; public static void main(String[] args) { creatGraph(); } static void creatGraph() { Scanner sc = new Scanner(System.in); V = sc.nextInt(); E = sc.nextInt(); Edges = new ArrayList[V]; for (int i = 0; i < V; i++) { Edges[i] = new ArrayList<Edge>(); } for (int i = 0; i < E; i++) { int u = sc.nextInt(); int v = sc.nextInt(); int w = sc.nextInt(); Edges[u].add(new Edge(v, w)); } for (ArrayList<Edge> i : Edges) { System.out.println(i); } } } class Edge { int v; int weight; public Edge(int v, int weight) { this.v = v; this.weight = weight; } @Override public String toString() { return "Edge{" + "v=" + v + ", weight=" + weight + '}'; } }