[关闭]
@zhangche0526 2017-02-25T06:34:47.000000Z 字数 803 阅读 804

拓扑排序

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cmath>
  4. #include<cstring>
  5. using namespace std;
  6. int m,n,list[101],p=0,head[101],indgr[101],edgenum;//indgr:入度
  7. struct node{int next,to;} edge[101];
  8. int stack[101],top=0;
  9. void push(int d){stack[++top]=d;}
  10. int pop(){return stack[top--];}
  11. void add(int x,int y)
  12. {
  13. edgenum++;
  14. edge[edgenum].to=y;
  15. edge[edgenum].next=head[x];
  16. head[x]=edgenum;
  17. indgr[y]++;
  18. }
  19. void rm(int en)//edgenum
  20. {
  21. edgenum--;
  22. indgr[edge[en].to]--;
  23. if(!indgr[edge[en].to])
  24. push(edge[en].to);
  25. if(edge[en].next)
  26. rm(edge[en].next);
  27. }
  28. void read()
  29. {
  30. cin >> n >> m;
  31. int u, v;
  32. for (int i = 1; i <= m; i++)
  33. {
  34. cin >> u >> v;
  35. add(u, v);
  36. }
  37. }
  38. void work()
  39. {
  40. //初始化stack
  41. for(int i=1;i<=n;i++)
  42. if(!indgr[i])
  43. push(i);
  44. while(top>0)
  45. {
  46. list[++p]=pop();
  47. rm(head[list[p]]);
  48. }
  49. if(!edgenum)
  50. cout<<"Circle";
  51. else for(int i=1;i<=p;i++) cout<<list[i];
  52. }
  53. int main()
  54. {
  55. freopen("tppx.in", "r", stdin);
  56. read();
  57. work();
  58. return 0;
  59. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注