- 用队列 + 链式前向星存边,每次删除入度为零的节点,并且更新它的边指向顶点的入度,直到队列为空。
import java.util.*; public class model { public static int n, count, cnt; public static class Edge { int to; int next; } public static Edge[] edges; public static int[] head, into, sort; public static void toposort() { cnt = 0; Queue<Integer> queue = new ArrayDeque<>(); //初始化:寻找入度为0的点 for (int i = 1; i <= n; i += 1) { if (into[i] == 0) { queue.offer(i); } } //循环,出队的点删掉边 while (!queue.isEmpty()) { int cur = queue.poll(); sort[cnt] = cur; cnt += 1; int index = head[cur]; while (index != -1) { into[edges[index].to] -= 1; if (into[edges[index].to] == 0) { queue.offer(edges[index].to); } index = edges[index].next; } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); count = 0; edges = new Edge[10000]; head = new int[n + 1]; Arrays.fill(head, -1); into = new int[n + 1]; sort = new int[n + 1]; for (int i = 1; i <= n; i += 1) { int to; while (true) { to = in.nextInt(); if (to == 0) { break; } edges[count] = new Edge(); edges[count].to = to; into[to] += 1; edges[count].next = head[i]; head[i] = count; count += 1; } } toposort(); for (int i = 0; i < n; i += 1) { System.out.print(sort[i] + " "); } } }
java | 拓扑排序模版
最新推荐文章于 2024-05-21 22:13:42 发布