拓扑排序

#include <iostream.h>
#include <malloc.h>
#define MAX 30
#define STACK_INIT_SIZE 30
#define STACKINCREASE 10
typedef struct
{
char *base;
char *top;
int stacksize;
}SqStack;
typedef struct 
{
int vexnum,arcnum;
char data[MAX];
int Graph[MAX][MAX];
int degree[MAX];
}MGraph;
int Locate(MGraph G,char s)
{
int i;
for(i=0;i<G.vexnum;i++)
{
if(G.data[i]==s)
{
return i;
break;
}
}
return -1;
}
void Create(MGraph &G)
{
int i,j,a,b;
char m,n;
cout<<"please input the vexnum and the arcnum:"<<endl;
cin>>G.vexnum>>G.arcnum;
cout<<"please input the data of the graph:";
for(i=0;i<G.vexnum;i++)
{
cin>>G.data[i];
G.degree[i]=0;
}
for(i=0;i<G.vexnum;i++)
{
for(j=0;j<G.vexnum;j++)
G.Graph[i][j]=0;
}
for(i=0;i<G.arcnum;i++)
{
cout<<"please input the vi-vj:";
cin>>m>>n;
a=Locate(G,m);
b=Locate(G,n);
G.Graph[a][b]=1;
G.degree[b]++;
}
}
int FindDegree(MGraph G)
{
int i;
for(i=0;i<G.vexnum;i++)
{
if(G.degree[i]==0)
{
return i;
break;
}
}
return -1;
}
bool InitStack(SqStack &S)
{
S.base=(char *)malloc(STACK_INIT_SIZE*sizeof(char));
if(!S.base) return false;
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return true;
}
bool Push(SqStack &S,char e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(char *)realloc(S.base,(S.stacksize+STACKINCREASE)*sizeof(char));
if(!S.base) return false;
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREASE;
}
*S.top++=e;
return true;
}
bool Pop(SqStack &S,char &e)
{
if(S.top==S.base) return false;
e=*(--S.top);
return true;
}
bool StackEmpty(SqStack S)
{
if(S.top==S.base)
return true;
else return false;
}
bool TopologicalSort(MGraph G)
{
int i,j,count;
char elem;
SqStack S;
InitStack(S);
for(i=0;i<G.vexnum;i++)
{
if(G.degree[i]==0) Push(S,G.data[i]);
}
count=0;
while(!StackEmpty(S))
{
Pop(S,elem);
cout<<elem<<"  ";
count++;
i=Locate(G,elem);
for(j=0;j<G.vexnum;j++)
{
if(G.Graph[i][j]!=0)
{
G.degree[j]--;
if(G.degree[j]==0) Push(S,G.data[j]);
}
}
}
if(count<G.vexnum) return false;
return true;
}
void main()
{
MGraph G;
Create(G);
cout<<"the TopologicalSort is:";
TopologicalSort(G);
cout<<endl;

}

这个是用邻接矩阵实现的拓扑排序,比较简单,可以给初学者参考参考

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值