拓扑排序--算法题
一. 题目
题目链接
二. 原理
拓扑排序的算法原理----多源BFS
数据结构是没有规定的, 根据需求选择即可, 一般为Map<Integer, List<Integer>> edges = new HashMap<>();
建图的同时, 统计入度情况
三. 代码
import java.util.*;
import java.io.*;public class Main {public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));public static Read in = new Read();public static void main(String[] args) throws IOException{int n = in.nextInt();int m = in.nextInt();int[] cnt = new int[n + 1];//统计入度, 下标表示点, 数值表示个数//建图Map<Integer, List<Integer>> edges = new HashMap<>();for(int i = 0; i < m; i++){int a = in.nextInt(), b = in.nextInt();if(!edges.containsKey(a)){edges.put(a, new ArrayList<>());}edges.get(a).add(b);cnt[b]++;}//拓扑排序Queue<Integer> queue = new LinkedList<>();for(int i = 1; i <= n; i++){if(cnt[i] == 0){queue.add(i);}}int[] res = new int[n];int pos = 0;while(!queue.isEmpty()){int tmp = queue.poll();res[pos++] = tmp;for(int a : edges.getOrDefault(tmp, new ArrayList<>())){//遍历map中tmp对应list的每一个数cnt[a]--;if(cnt[a] == 0){queue.add(a);}}}if(pos == n){for(int i = 0; i < pos - 1; i++){out.print(res[i] + " ");}out.print(res[pos - 1]);}else{out.println(-1);}out.close();}}class Read {StringTokenizer st = new StringTokenizer("");BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));String next() throws IOException {while (!st.hasMoreTokens()) {st = new StringTokenizer(bf.readLine());}return st.nextToken();}String nextLine() throws IOException {return bf.readLine();}int nextInt() throws IOException {return Integer.parseInt(next());}long nextLong() throws IOException {return Long.parseLong(next());}Double nextDouble() throws IOException {return Double.parseDouble(next());}
}