拓扑排序

//
// Created by dgm on 19-4-1.
//

#include <iostream>
using namespace std;
#define MaxNum 100
//use adjacency list to store graph
typedef struct EdgeNode{     //edge
    int weight;
    int adjvex;
    EdgeNode* next;
}EdgeNode;

typedef struct VertexNode{  //vertex
    int data;
    int in=0;               //count indregee
    EdgeNode*firstedge;
}AdjList[MaxNum];

typedef struct {
    AdjList adjlist;
    int vexnum,edgenum;
}ALGraph;

void CreateALGraph(ALGraph &G)
{
    cout<<"vexnums&edgenums:"<<endl;
    cin>>G.vexnum>>G.edgenum;
    cout<<"vertexs:"<<endl;
    for (int i = 0; i < G.vexnum; ++i){
        cin>>G.adjlist[i].data;
        G.adjlist[i].firstedge=NULL;
    }
    cout<<"i,j,weight"<<endl;
    EdgeNode* p;
    for (int i = 0; i < G.edgenum; ++i) {
        int posx,posy,weight;
        cin>>posx>>posy>>weight;    //from i points to j
        p=new EdgeNode;
        p->adjvex=posy;p->weight=weight;
        p->next=G.adjlist[posx].firstedge;
        G.adjlist[posx].firstedge=p;
        G.adjlist[posy].in++;   //increase j's indregee
    }
}

//void PrintALGraph(ALGraph G)
//{
//    for (int i = 0; i < G.vexnum; ++i) {
//        auto p=G.adjlist[i].firstedge;
//        while(p){
//            cout<<"<"<<G.adjlist[i].data<<","<<p->adjvex<<">"<<"  "<<p->weight<<endl;
//            p=p->next;
//        }
//    }
//}

int TopoSort(ALGraph G)
{
    int count=0;
    int *stack;
    int gettop=0;
    stack=(int*)malloc(G.vexnum* sizeof(int));
    int top=0;
    for (int i = 0; i < G.vexnum; ++i)
        if (!G.adjlist[i].in)
            stack[++top]=i;  //初始时入度为零的“活动”没有先决条件,入栈
    while(top)    //遍历只以活动stack[top]为先决条件的顶点(活动)
                  //如果没有这样的顶点,在对邻接点入度-1后遍历stack[top--]
    {
        count++;
        gettop=stack[top--];
        cout<<G.adjlist[gettop].data<<" ";
        for (auto e = G.adjlist[gettop].firstedge; e  ; e=e->next) {
            auto k=e->adjvex;
            if (!(--G.adjlist[k].in))   //必须要把这个顶点的所有先决条件(活动)遍历之后
                                        //才能遍历这个顶点
                stack[++top]=k;
        }
    }
    if(count!=G.vexnum) {  //当存在环时,while循环无法遍历这个环
        //所以不能遍历全部顶点,返回-1
        cout<<"error, cyclic graph"<<endl;
        return -1;
    }
    return 1;
}

int main()
{
    ALGraph G;
    CreateALGraph(G);
    TopoSort(G);
    return 0;
}

在这里插入图片描述在这里插入图片描述在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值