拓扑排序模板
/*邻接表拓扑排序模板*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=15;//顶点最大数目
struct Arcnode
{
int to;
struct Arcnode *next;
};
int n,m;//顶点,边数
Arcnode* List[maxn];//每个顶点的边链表表头指针
int cunt[maxn];//各顶点的入度
char output[100];//输出内容
void Topsort()
{
int top=-1;
Arcnode* temp;
bool sign=false;//判断是否出现有向环
int pos=0;//output数组的位置
for(int i=0;i<n;i++)//入队为0入栈
{
if(cunt[i]==0)
{
cunt[i]=top;
top=i;
}
}
for(int i=0;i<n;i++)
{
if(top==-1)
{
sign=true;
break;
}
else
{
int j=top;//出栈+遍历
top=cunt[top];
pos+=sprintf(output+pos,"%d ",j+1);
temp=List[j];
while(temp!=NULL)
{
int k=temp->to;
if(--cunt[k]==0)
{
cunt[k]=top;
top=k;
}
temp=temp->next;
}
}
}
if(sign)
cout<<"Network has a cycle!"<<endl;
else
{
int len=strlen(output);
output[len-1]=0;
cout<<output<<endl;
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
if(!(n||m))
break;
memset(List,0,sizeof(List));
memset(cunt,0,sizeof(cunt));
memset(output,0,sizeof(output));
Arcnode* temp;
int u,v;
for(int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
u--;
v--;
cunt[v]++;
temp=new Arcnode;
temp->to=v;//构造邻接表
temp->next=NULL;
if(List[u]==NULL)//边链表没有节点
List[u]=temp;
else//边链表有节点
{
temp->next=List[u];
List[u]=temp;
}
}
Topsort();
for(int i=0;i<n;i++)//释放存储空间
{
temp=List[i];
while(temp!=NULL)
{
List[i]=temp->next;
delete temp;
temp=List[i];
}
}
}
return 0;
}