| import java.io.*; |
| import java.util.*; |
| |
| public class Main { |
| |
| public static int n = 100001; |
| public static int m = 100001; |
| |
| public static ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); |
| |
| public static PriorityQueue<Integer> heap = new PriorityQueue<>(); |
| |
| public static int[] indegree = new int[n]; |
| |
| public static int[] ans = new int[n]; |
| |
| public static int cnt = 0; |
| |
| public static void build() { |
| graph.clear(); |
| heap.clear(); |
| cnt = 0; |
| for (int i = 0; i < n; i++) { |
| graph.add(new ArrayList<>()); |
| } |
| } |
| |
| public static void main(String[] args) throws IOException { |
| BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| StreamTokenizer in = new StreamTokenizer(br); |
| PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); |
| while (in.nextToken() != StreamTokenizer.TT_EOF) { |
| n = (int) in.nval + 1; |
| in.nextToken(); |
| m = (int) in.nval; |
| build(); |
| for (int i = 0, from, to; i < m; i++) { |
| in.nextToken(); |
| from = (int) in.nval; |
| in.nextToken(); |
| to = (int) in.nval; |
| addEdge(from, to); |
| indegree[to]++; |
| } |
| topoSort(); |
| for (int i = 0; i < n; i++) { |
| out.print(ans[i] + " "); |
| } |
| out.println(ans[n - 1]); |
| } |
| out.flush(); |
| out.close(); |
| br.close(); |
| } |
| |
| private static void topoSort() { |
| for (int i = 1; i < n; i++) { |
| if (indegree[i] == 0) { |
| heap.add(i); |
| } |
| } |
| while (!heap.isEmpty()) { |
| int cur = heap.poll(); |
| ans[cnt++] = cur; |
| for (int i : graph.get(cur)) { |
| indegree[i]--; |
| if (indegree[i] == 0) { |
| heap.add(i); |
| } |
| |
| } |
| } |
| |
| } |
| |
| private static void addEdge(int from, int to) { |
| graph.get(from).add(to); |
| } |
| } |

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统