拓扑排序 C、C++

#include <cstdio>
#include <cstdlib>
#include <stack>
#define Max 100
#define Maxint 100000
using namespace std;
typedef struct ArcNode
{
    int adjex;
    int weight;
    struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode
{
    int in;
    ArcNode *firstarc;
}VNode;
typedef struct
{
    int vex,arc;
    VNode vertices[Max];
}ALGraph;
void CreatALGraph(ALGraph &G)
{
     printf("顶点数:");
     scanf("%d",&G.vex);
     printf("边数:");
     scanf("%d",&G.arc);
     int i;
     for(i=0;i<G.vex;i++)
     {
         G.vertices[i].in=0;
         G.vertices[i].firstarc=NULL;
     }//初始化
     for(i=0;i<G.arc;i++)
     {
         int e1,e2;
         int weight;
         printf("顶点->权值->顶点:");
         scanf("%d%d%d",&e1,&weight,&e2);
         G.vertices[e2].in++;
         ArcNode *p=NULL;
         p=new ArcNode;
         p->adjex=e2;
         p->weight=weight;
         p->nextarc=G.vertices[e1].firstarc;
         G.vertices[e1].firstarc=p;
     }
}
int TopologicalSort(ALGraph &G,int topo[])
{
    stack <int> S;
    int i,count=0;
    for(i=0;i<G.vex;i++)
        if(!G.vertices[i].in)
            S.push(i);
    while(!S.empty())
    {
        int e=S.top();
        topo[count++]=e;
        S.pop();
        ArcNode *p=NULL;
        p=new ArcNode;
        p=G.vertices[e].firstarc;
        while(p)
        {
            int k=p->adjex;
            --G.vertices[k].in;
            if(!G.vertices[k].in) S.push(k);
            p=p->nextarc;
        }
    }
    if(count<G.vex) return 0;
    else return 1;
}
int main()
{
    ALGraph G;
    int topo[Max];
    CreatALGraph(G);
    if(TopologicalSort(G,topo))
        for(int i=0;i<G.vex;i++)
            printf("%-4d",topo[i]);
    else printf("ERROR!");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值