fork(5) download
  1. #include<stdio.h>
  2. #include<iostream>
  3. #include<queue>
  4.  
  5. using namespace std;
  6.  
  7. #define MAX 100
  8. #define initial 1
  9. #define visited 2
  10.  
  11. int arr[MAX][MAX],n,topo_order[MAX],indeg[MAX]={0};
  12.  
  13. queue<int> myque;
  14.  
  15. void createGraph()
  16. {
  17. printf("enter the number of edges : ");
  18. scanf("%d",&n);
  19. int i,src,dest,edge=n*(n-1);
  20. for(i=0;i<edge;i++)
  21. {
  22. printf("enter the source and destination or(-1,-1) to quit : ");
  23. scanf("%d %d",&src,&dest);
  24. if(src==-1 && dest==-1)
  25. break;
  26. else if(src>=n||src<0||dest>=n||dest<0)
  27. {
  28. printf("invalid input\n");
  29. i--;
  30. }
  31. else
  32. {
  33. arr[src][dest]=1;
  34. indeg[dest]++;
  35. }
  36. }
  37. }
  38.  
  39. void toposort()
  40. {
  41. int i,count=0,v,j=0;
  42. for(i=0;i<n;i++)
  43. if(indeg[i]==0)
  44. myque.push(i);
  45. while(!myque.empty() && count<n)
  46. {
  47. v=myque.front();
  48. topo_order[j]=v;
  49. j++;
  50. myque.pop();
  51. for(i=0;i<n;i++)
  52. {
  53. if(arr[v][i]==1)
  54. {
  55. arr[v][i]=0;
  56. indeg[i]--;
  57. if(indeg[i]==0)
  58. myque.push(i);
  59. }
  60. }
  61. }
  62. for(i=0;i<n;i++)
  63. printf("%d ",topo_order[i]);
  64. }
  65.  
  66.  
  67. int main()
  68. {
  69. createGraph();
  70. toposort();
  71. return 0;
  72. }
  73.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
enter the number of edges :