#include <iostream>
using namespace std;
#define MaxVertexNum 100
typedef struct Graph{
int edge[MaxVertexNum][MaxVertexNum];
int vexnum;//顶点数
}; //图的邻接矩阵存储
//栈
typedef struct SqStack{
int data[MaxVertexNum];
int top;
};
void InitStack(SqStack &S){
S.top=-1;
}
bool IsEmpty(SqStack S){
if(S.top==-1){
return 1;
}else{
return 0;
}
}
bool Push(SqStack &S,int x){
if(S.top==MaxVertexNum-1)
return false;
S.data[++S.top]=x;
return true;
}
bool Pop(SqStack &S,int &x){
if(S.top==-1)
return false;
x=S.data[S.top--];
return true;
}
bool TopologicalSort(Graph G,SqStack &S){
InitStack(S);
int i,j;
int indegree[G.vexnum]={0};
for(j=0;j<G.vexnum;j++){
for(i=0;i<G.vexnum;i++){
if(G.edge[i][j]!=0){
indegree[j]++;
}
}
}//统计入度
for(i=0;i<G.vexnum;i++){
if(indegree[i]==0)
Push(S,i);
}
// for(i=0;i<G.vexnum;i++){
// printf("%d ",indegree[i]);
// }
int count=0;
while(!IsEmpty(S)){
Pop(S,i);
printf("%d ",i);
count++;
for(j=0;j<G.vexnum;j++){
if(G.edge[i][j]!=0){
indegree[j]--;
if(indegree[j]==0){
Push(S,j);
}
}
}
}
if(count<G.vexnum){
return false;
}
else{
return true;
}
}
bool InitGraph(Graph &G){
G.vexnum=5;
//0 3 1 0 0
//0 0 4 5 0
//0 0 0 6 7
//0 0 0 0 2
//0 0 0 0 0
for(int i=0;i<G.vexnum;i++){
for(int j=0;j<G.vexnum;j++){
G.edge[i][j]=0;
}
}
G.edge[0][1]=3;
G.edge[0][2]=1;
G.edge[1][2]=4;
G.edge[1][3]=5;
G.edge[2][3]=6;
G.edge[2][4]=7;
G.edge[3][4]=2;
}
int main() {
Graph G;
SqStack S;
InitGraph(G);
// for(int i=0;i<G.vexnum;i++){
// for(int j=0;j<G.vexnum;j++){
// printf("%d ",G.edge[i][j]);
// }
// printf("\n");
// }
TopologicalSort(G,S);
return 0;
}