有向图的拓扑序列

有向图的拓扑序列


有向无环图称之为拓扑图。

有向图的拓扑序列_第1张图片

import java.util.*;
public class Main{
     
    static int[] h = new int[100010];
    static int[] nodes = new int[100010];
    static int[] next = new int[100010];
    static int index = 1;
    static int[] d = new int[100010];
    static int[] q = new int[100010];
    static int head=0;
    static int tail = -1;
    static int n;
    static void add(int a,int b){
     
        nodes[index] = b;
        next[index] = h[a];
        h[a] = index++;
    }
    //核心代码
    static boolean topSort(){
     
        for(int i=1;i<=n;i++){
     
            if(d[i]==0) q[++tail] = i;
        }
        while(head<=tail){
     
            int t = q[head++];
            for(int i=h[t];i!=-1;i=next[i]){
     
                d[nodes[i]]--;
                if(d[nodes[i]]==0){
     
                    q[++tail] = nodes[i];
                }
            }
        }
        return tail==n-1;
    }
    public static void main(String[] agrs){
     
        Scanner scan =  new Scanner(System.in);
        n = scan.nextInt();
        int m = scan.nextInt();
        int a,b;
        for(int i=1;i<=n;i++){
     
            h[i] = -1;
        }
        for(int i=1;i<=m;i++){
     
            a = scan.nextInt();
            b = scan.nextInt();
            add(a,b);
            d[b]++;
        }
        
        if(!topSort()){
     
            System.out.print(-1);
        }else{
     
            for(int i=0;i<=n-1;i++){
     
                System.out.print(q[i]+" ");
            }
        }
    }
}

你可能感兴趣的:(算法导论)