本题具有特定关系的排序,使用拓扑排序法,
话不多说,上代码(java)
package cn.hncu.search;
import java.util.Scanner;
public class TopologySort {
static Scanner sc;
static int[][] matrix;
static int[] degree;
static boolean[] isInOrder;
static int n,m;
public static void main(String[] args) {
sc=new Scanner(System.in);
while(sc.hasNext()){
n=sc.nextInt();
m=sc.nextInt();
init();
topology();
}
}
//拓扑排序
private static void topology() {
int count=0;//记录已排序个数
boolean flag=false;//检查是否存在回路
while (true) {
flag=false;
for (int i = 0; i < n; i++) {
if (degree[i] == 0 && !isInOrder[i]) {//符合要求
count++;
flag=true;
//更新元素是否排序记录表
isInOrder[i] = true;
//输出该元素
System.out.print(i+1);
if (count < n)
System.out.print(" ");
else {
System.out.println();
return;//排序完成
}
//更新入度排序表
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 1)
degree[j]--;
}
break;//使得能排出的按从小到大输出
}
}
if(!flag&&count<n){
System.out.println("存在回路,无法排序完成");
return;
}
}
}
//初始化 构造邻接矩阵,元素入度记录表,元素是否排序记录表
private static void init() {
matrix=new int[n][n];
degree=new int[n];
isInOrder=new boolean[n];
//邻接矩阵
for (int i = 0; i < m; i++) {
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
if(matrix[a][b]==0){
matrix[a][b]=1;//邻接矩阵
degree[b]++;//元素入度记录表
}
}
}
}