//
// 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;
}
拓扑排序
最新推荐文章于 2025-05-13 21:35:52 发布