#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;
}
拓扑排序 C、C++
最新推荐文章于 2024-03-06 16:08:29 发布