#include<bits/stdc++.h>
using namespace std;
int v,e,x,y,indegree[100],ans[100],t=1;
typedef struct ANode
{
int adjvex;
struct ANode *next;
}ANode;
struct VNode
{
int date;
ANode *first;
}V[100];
typedef struct Stack
{
int date[100];
int top;
}Stack;
void InitStack(Stack &S)
{
S.top=-1;
}
void Push(Stack &S,int n)
{
S.top++;
S.date[S.top]=n;
}
int Pop(Stack &S)
{
int x=S.date[S.top];
S.top--;
return x;
}
int Empty(Stack &S)
{
if(S.top==-1)
return 1;
else
return 0;
}
void GreateGrape()//有向图邻接表
{
cin>>v>>e;
for(int i=1;i<=v;i++)
{
cin>>V[i].date;
V[i].first=NULL;
}
for(int i=0;i<e;i++)
{
cin>>x>>y;
indegree[y]++;//入度
ANode *s=new ANode;//插入边链表
s->adjvex=y;
s->next=V[x].first;
V[x].first=s;
}
}
void TopologicalSort()//拓扑排序
{
Stack S;
InitStack(S);
for(int i=1;i<=v;i++)
if(!indegree[i])
Push(S,i);
while(!Empty(S))
{
int x=Pop(S);
ans[t]=x;
t++;
ANode *p;
p=V[x].first;//p指向vx的第一个邻接表
while(p!=NULL)//删除顶点以及以它为尾的操作通过弧头顶点的入度减1实现
{
int y=p->adjvex;
indegree[y]--;
if(!indegree[y])
Push(S,y);
p=p->next;
}
}
if(t-1==v)
{
cout<<"无回路,拓扑排序为:"<<endl;
for(int i=1;i<=v;i++)
cout<<"v"<<ans[i]<<" ";
}
}
int main()
{
GreateGrape();
TopologicalSort();
return 0;
}
/*
12 16
1 2 3 4 5 6 7 8 9 10 11 12
1 4
1 2
1 3
1 12
4 5
2 3
3 5
3 7
5 7
3 8
9 12
9 10
10 12
9 11
11 6
6 8
*/
拓扑排序
最新推荐文章于 2023-11-01 21:15:00 发布