static boolean topsort() {
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];
if(-- d[j] == 0)
q[++ tt] = j;
}
}
return tt == n - 1;
}
例题
3696. 构造有向无环图
import java.io.*;
import java.util.*;
import java.util.logging.StreamHandler;
public class Main {
static int N = 200010;
static int M = 200010;
static int []h = new int [N];
static int []e = new int [M];
static int []ne = new int [M];
static int [] q = new int [N];
static int []d = new int [N];
static int pos[] = new int[M];
static int n,m,idx;
static Edge edge[] = new Edge[N];
static BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static boolean topsort() {
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];
if(-- d[j] == 0)
q[++ tt] = j;
}
}
return tt == n - 1;
}
static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
public static void main(String[] args) throws IOException {
int T = Integer.parseInt(re.readLine());
while(T --> 0) {
idx = 0;
int cnt = 0;
Arrays.fill(h, -1);
Arrays.fill(d, 0);
String split[] = re.readLine().split(" ");
n = Integer.parseInt(split[0]);
m = Integer.parseInt(split[1]);
while(m --> 0) {
String split2[] = re.readLine().split(" ");
int t = Integer.parseInt(split2[0]);
int x = Integer.parseInt(split2[1]);
int y = Integer.parseInt(split2[2]);
if(t == 0) {
edge[cnt ++] = new Edge(x,y);
}else {
add(x,y);
d[y] ++;
}
}
if(!topsort()) {
System.out.println("NO");
}else {
System.out.println("YES");
for(int i = 1; i <= n; i ++ ) {
for(int j = h[i]; j != -1; j = ne[j]) {
System.out.println(i + " " + e[j]);
}
}
for(int i = 0; i < n; i ++ ) pos[q[i]] = i;
for(int i = 0; i < cnt; i ++ ) {
int a = edge[i].a;
int b = edge[i].b;
if(pos[a] > pos[b]) {
int t = a;
a = b;
b = t;
}
System.out.println(a + " " + b);
}
}
}
pw.close();
}
}
class Edge{
int a,b;
public Edge(int a, int b) {
super();
this.a = a;
this.b = b;
}
public Edge() {
}
}