Cause of this semester we will do the single chip microcomputer, It’s very very difficult, using C to program. I hope I will pass the Exam and Project! And maybe have not a long time to practice, but I will try my best to come on.
This module, said problem is more suitable…
is about the Topology, is just allowed from after going list in graph.
Okey, we can pay attention on the problem.
Problem in AcWing
Thinking is to use the knowledge in Data Structure : Indegree and Outdegree(if u donot know what the damn is, then can google it, very simple. or I can tell u)
Indegree : the number of lines will go to a point.
Outdegree : same , the number of lines will leave from a point.
Use an array to sum the points’ Indegree.To sum all the ways that is topology.
We can see the code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 100010, n, m, idx;
static int h[] = new int[N], e[] = new int[N], ne[] = new int[N], q[] = new int[N], d[] = new int[N];
public static void main(String[] args) throws Exception {
String nm[] = br.readLine().split(" ");
n = Integer.parseInt(nm[0]);
m = Integer.parseInt(nm[1]);
Arrays.fill(h, -1);
for (int i = 0; i < m; i++) {
String ss[] = br.readLine().split(" ");
int a = Integer.parseInt(ss[0]);
int b = Integer.parseInt(ss[1]);
add(a, b);
d[b]++;
}
if (topology()) {
for (int i = 0; i < n; i++) pw.print(q[i] + " ");
} else pw.println(-1);
pw.flush();
br.close();
}
private static boolean topology() {
int hh = 0, tt = -1;
for (int i = 1; i <= n; i++)
if (d[i] == 0)
q[++tt] = i;
while (hh <= tt) {
int t = q[hh++];
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
d[j] --;
if (d[j] == 0) q[++tt] = j;
}
}
return tt == n - 1;
}
private static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}