#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<string> #include<cmath> #include<map> using namespace std; const int maxn=10; struct ArcNode { int to; struct ArcNode *next; }; int n,m;//顶点个数,边数 ArcNode* List[maxn];//各顶点边链表的表头指针 int count[maxn];//各顶点入度 char output[100];//输出内容 void TopSort() { int top=-1; ArcNode* temp; bool cycle=false;// int pos=0;//写入output数组的位置 for(int i=0; i<n; i++) { if(count[i]==0) { count[i]=top; top=i; } } for(int i=0; i<n; i++) { if(top==-1)//栈为空,有回路 { cycle=true; break; } else { int j=top;//栈顶顶点j出栈 top=count[top];// pos+=sprintf(output+pos,"%d ",j+1); temp=List[j];//遍历顶点j的边链表,每条出边的终点的入度减1 while(temp!=NULL) { int k=temp->to; if(--count[k]==0)//终点入度减至0,则入栈 { count[k]=top; top=k; } temp=temp->next; } } } if(cycle) printf("Network has a cycle!\n"); else { int len=strlen(output); output[len-1]=0;//去掉最后的空格 printf("%s\n",output); } for(int i=0; i<n; i++)//释放边链表的存储空间 { temp=List[i]; while(temp!=NULL) { List[i]=temp->next; delete temp; temp=List[i]; } } } int main() { int u,v; while(1) { scanf("%d%d",&n,&m); if(n==0 && m==0) break; memset(List,0,sizeof(List)); memset(count,0,sizeof(count)); memset(output,0,sizeof(output)); ArcNode* temp; for(int i=0; i<m; i++)//构造边链表 { scanf("%d%d",&u,&v);//读入边的起点和终点 u--; v--; count[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(); } return 0; }
纯属无聊。。。