AcWing 848. JAVA:有向图的拓扑序列
原题链接
简单
作者:
ARM
,
2020-08-10 20:39:22
,
所有人可见
,
阅读 529
java 代码
import java.io.*;
import java.lang.*;
import java.util.*;
class Main{
static int n = 0, m = 0, N = 100010;
static int[] h = new int[N];//邻接表数组
static int[] e = new int[N], ne = new int[N];//单链表
static int idx = 1;
static int[] q = new int[N], out = new int[N], in = new int[N];
static void add(int a, int b){
e[idx] = b; ne[idx] = h[a]; h[a] = idx++;
out[a]++;//初度+1
in[b]++;//入度+1
}
static boolean sort(){
int hh = 0, tt = -1;
for(int i = 1; i <= n; ++i){//所有入度为0的先进入队列
if(in[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];
if(in[j] != 0){
in[j]--;
out[t]--;
}
if(in[j] == 0){
q[++tt] = j;
}
}
}
return tt == n - 1;
}
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String[] params = buf.readLine().split(" ");
n = Integer.valueOf(params[0]);
m = Integer.valueOf(params[1]);
Arrays.fill(h, -1);
for(int i = 1; i <= m; ++i){
String[] info = buf.readLine().split(" ");
int a = Integer.valueOf(info[0]);
int b = Integer.valueOf(info[1]);
add(a, b);//有向图
}
int t = 0;
if(sort()){
while(n-- != 0){
System.out.print(q[t++] + " ");
}
}else{
System.out.print(-1);
}
}
}