#include
#includeusingnamespacestd;typedefcharVertexType;typedefintInfoType;constintMax_VERTEX_NUM=20;typedefstructArcNode{intadjvex;ArcNodenextarc;InfoTypeinfo;}ArcNode;typedefstruct{VertexTypedata;ArcNodefirstarc;}VNode,AdjList[Max_VERTEX_NUM];typedefstruct{AdjListvertices;intvexnum,arcnum;intkind;}ALGraph;intLocateVex(ALGraph&G,VertexTypev){inti;for(i=0;iG.vertices[i].data)break;}if(i>=G.vexnum){找不到,返回-1
returni;}voidCreateDG(ALGraph&G){//采用邻接表表示法,构建图VertexTypev1,v2;boolIncInfo;inti,j,k;cout<<“请依次输入有向图G的顶点数、弧数、弧信息标志(1或0):”;cin>>G.vexnum>>G.arcnum>>IncInfo;//IncInfo为0表示各弧不含相关信息cout<<“请输入各顶点信息:”;for(i=0;i>G.vertices[i].data;G.vertices[i].firstarc=NULL;}cout<<“输入弧(共”<>v1>>v2;j=LocateVex(G,v1);k=LocateVex(G,v2);if(j-1||k==-1)return;ArcNodeq=G.vertices[j].firstarc;ArcNodep=newArcNode;if(!q){G.vertices[j].firstarc=p;}else{while(q->nextarc)q=q->nextarc;q->nextarc=p;}p->adjvex=k;p->info=NULL;p->nextarc=NULL;}}//CreateDGvoidDisplayElem(VertexTypev){
cout<";for(ArcNodep=G.vertices[i].firstarc;p;p=p->nextarc){coutp=G.vertices[i].firstarc;p;p=p->nextarc){InDegree[p->adjvex]++;}}}intFirstDegree0(ALGraph&G){for(inti=0;i0)returni;}return-1;}boolTopSort(ALGraph&G){//各结点入度记录intm=0;CountInDegree(G);intv=FirstDegree0(G);while(v!=-1){DisplayElem(G.vertices[v].data);tag[v]=true;;
if(mG.vexnum){cout<p=G.vertices[v].firstarc;p;p=p->nextarc){intw=p->adjvex;if(tag[w]==false)InDegree[w]–;}v=FirstDegree0(G);}if(m拓扑排序”<