/*
输入边,建立邻接表,出边表;
拓扑排序:找出入度为零的顶点,删除之,及其出边,
更新相邻顶点入度;
重复上过程,直到栈为空(栈用来保存度为零的顶点)
或待输出顶点数小于输入顶点,有环。
*/
#include<iostream>
#include<stack>
using namespace std;
const int MAXN=10;
int n,m;
int OUT[MAXN]; //output record
struct ArcNode
{
int v;
ArcNode * next;
ArcNode( int to):v(to){next=NULL;}
};
struct ArcNode* V[MAXN+1];
int count[MAXN+1];
stack<int> stk;
void addV(int from,int to);
void deleteV(int from);
void addV(int from,int to)
{
ArcNode *p= new ArcNode(to);
p->next=V[from];
V[from]=p;
count[to]++;
}
void deleteV(int from)
{
ArcNode *p=V[from];
while(p!=NULL)
{
V[from]=p->next;
count[p->v]--;
delete p;
p=V[from];
}
}
int main()
{
int from,to;
int output; //record how many V has been output
while(cin>>n>>m,(n+m)!=0)
{
output=-1;
for(int i=0;i<m;i++)
{
cin>>from>>to;
addV(from,to);
}
for(int j=1;j<=n;j++)
if(count[j]==0)
{
stk.push(j);
count[j]=-1;
}
while(!stk.empty())
{
int point=stk.top();stk.pop();
OUT[++output]=point;
deleteV(point);
for(int k=1;k<=n;k++)
if(count[k]==0)
{
stk.push(k);
count[k]=-1;
}
}
if(output+1==n)
{
for(int i=0;i<=output;i++)
if(i==0)
cout<<OUT[i];
else cout<<" " <<OUT[i];
}
else cout<<"Network has a cycle!" ;
cout<<endl;
for(int i=1;i<=n;i++) //删除邻接表(有环可能)
deleteV(i);
}
return 0;
}
拓扑排序
最新推荐文章于 2023-01-31 14:10:48 发布