有向无环图 JAVA&C++

给定一个包含n个点m条边的有向无环图,求出该图的拓扑序。若图的拓扑序不唯一,输出任意合法的拓扑序即可。若该图不能拓扑排序,输出-1。

第一行输入两个整数n,m(1≤n,m≤2·105),表示点的个数和边的条数。接下来的m行,每行输入两个整数ui,vi(1≤u,v≤n),表示ui 到vi之间有一条有向边。

JAVA实现

import java.io.*;
import java.util.*;
public class Main {
    /**
     * 拓扑序
     */
    static List<Integer> ans = new ArrayList<>();
 
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] line = reader.readLine().split(" ");
        // 存储点的出度集合
        List<List<Integer>> graph = new ArrayList<>();
        // 点数
        int n = Integer.parseInt(line[0]);
        // 边数
        int m = Integer.parseInt(line[1]);
        // 存储点的入度数
        int[] inDegree = new int[n];
        // 初始化点
        for (int i = 0; i < n; i++) {
            // 此处由于点的出度可能有多个,则使用list初始化
            graph.add(new ArrayList<>());
        }
        for (int i = 0; i < m; i++) {
            line = reader.readLine().split(" ");
            // 边的起始点
            int u = Integer.parseInt(line[0]);
            // 边的结束点
            int v = Integer.parseInt(line[1]);
            // v点入度+1
            inDegree[v - 1]++;
            // u点增加出度,指向v点
            graph.get(u - 1).add(v - 1);
        }
        boolean flag = topologicalSort(graph, inDegree);
        if (flag) {
            // 是有向无环图,输出拓扑排序
            for (int i = 0; i < ans.size(); i++) {
                writer.write(String.valueOf(ans.get(i)));
                if (i != n - 1) {
                    writer.write(" ");
                }
            }
        } else {
            writer.write("-1");
 
        }
        writer.flush();
        writer.close();
 
    }
 
    public static boolean topologicalSort(List<List<Integer>> graph, int[] inDegree) {
        int num = 0;
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < inDegree.length; i++) {
            // 先找入度为0的点,放入队列
            if (inDegree[i] == 0) {
                deque.offer(i);
 
            }
        }
        while (!deque.isEmpty()) {
            int u = deque.poll();
            // 入度为0的点为起始点
            ans.add(u + 1);
            for (int i = 0; i < graph.get(u).size(); i++) {
                // 获取入度为0的点的出度点
                int v = graph.get(u).get(i);
                // 这个点的入度减1
                inDegree[v]--;
                // 寻找下一个入度为0的点
                if (inDegree[v] == 0) {
                    deque.offer(v);
                }
            }
            graph.get(u).clear();
            num++;
        }
        return num == inDegree.length;
    }
}

C++实现 

C++实现 

#include<stdlib.h>
 
typedef struct EdgeNode{
    int adjext;
    struct EdgeNode* next;
}EdgeNode;
 
typedef struct VerteNode{
    int in;
    int data;
    struct VerteNode* firstEdge;
}VerteNode;
 
typedef struct{
    VerteNode adjList[200000];
    int numsNode,numsEdge;
}GraphAdjList;
 
int nums=0;
 
void CreateALGraph(GraphAdjList* G){
    int i,j,k;
    for(i=0;i<G->numsNode;i++){
        G->adjList[i].data=i;
        G->adjList[i].firstEdge=NULL;
        G->adjList[i].in=0;
    }
    for(k=0;k<G->numsEdge;k++){
        EdgeNode* e;
        scanf("%d",&i);
        scanf("%d",&j);
        e=(EdgeNode*)malloc(sizeof(EdgeNode));
        e->adjext=j-1;
        e->next=G->adjList[i-1].firstEdge;
        G->adjList[i-1].firstEdge=e;
        G->adjList[j-1].in++;
    }
}
 
int TopologicalSort(GraphAdjList* G,int* ans){
    int i,j,gettop;
    int top=0;
    EdgeNode* e;
    int count=0;
    int* Queue=(int*)malloc(sizeof(int)*G->numsNode);
    int front=0,rear=0;
    for(int i=0;i<G->numsNode;i++){
        if(G->adjList[i].in==0)
            Queue[rear++]=i;
    }
    while(front!=rear){
        gettop=Queue[front++];
        ans[nums++]=G->adjList[gettop].data+1;
        count++;
        for(e=G->adjList[gettop].firstEdge;e;e=e->next){
            j=e->adjext;
            if(!(--G->adjList[j].in))
               Queue[rear++]=j;
        }
    }
    if(count==G->numsNode)
        return 1;
    else
        return -1;
}
 
int main(){
    GraphAdjList* G=(GraphAdjList*)malloc(sizeof(GraphAdjList));
    scanf("%d",&G->numsNode);
    scanf("%d",&G->numsEdge);
    int* ans=(int*)malloc(sizeof(int)*G->numsNode);
    CreateALGraph(G);
    int flag=TopologicalSort(G,ans);
    if(flag==-1)
        printf("-1");
    else{
        for(int i=0;i<nums;i++){
            if(i==0)
                printf("%d",ans[i]);
            else
                printf(" %d",ans[i]);
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值