Applications that have a sort of forward topology
First enter n points, indicating that there are n vertices in the direction graph, the next n rows, each row entered a few numbers, the number of line I indicates that they are the successor of vertex I, the output requires that the number of the line to be in front of these numbers, when the number is 0 o'clock, indicates that I point no successor node. is to require the output of the topological sequence of the graph.
[input/output]: [Example]:
Sample Input
5
0
4 5 1 0
1 0
5 3 0
3 0
Sample Output
2 4 5) 3 1
PackageMain;ImportJava.util.PriorityQueue;ImportJava.util.Queue;ImportJava.util.Scanner; Public classMain {Private intN; Private int[][]g;//adjacency Matrix Private int[] indegree;//the degree of vertex penetration PrivateQueue<integer>que; Private int[] result;//Save Results PublicMain (intNint[] Indegree,int[][]g) { This. n=N; This. Indegree =Indegree; This. G =G; } Public Static voidMain (string[] args) {//outputs a fixed-point-first topological order with no precursors, and each step of the method always outputs a vertex without a precursor at the momentScanner input =NewScanner (system.in); intn,x; int[][]g; int[] indegree; while(Input.hasnext ()) {n=Input.nextint (); Indegree=New int[N+1]; G=New int[N+1] [N+1]; for(inti=1;i<=n;i++) { for(intj=1;j<=n;j++) {x=Input.nextint (); if(x = = 0) { Break; } G[i][x]= 1; INDEGREE[X]++; }} Main ma=NewMain (N,INDEGREE,G); Ma.toposort (); } } Private voidToposort () {intR=1; Que=Newpriorityqueue< integer>(); Result=New int[N+1]; for(inti = 1; I <=n; i++) { if(Indegree[i] = = 0)//queue with a vertex with a 0-degree entryQue.add (i); } //for (int i=1;i<=n;i++)//System.out.print (Indegree[i]); while(!Que.isempty ()) { intv = que.poll ();//out TeamResult[r++]=v;//Save V to result set for(inti = 1; I <=n; i++) {//deletes the vertex v and the arc with the tail at v. if(G[v][i] = = 1) {Indegree[i]--;//simulate deleting edges if(Indegree[i] = = 0) Que.add (i); } } } for(inti=1;i<=n;i++) System.out.print (Result[i]+" "); }}
Applications that have a sort of forward topology