fork download
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #define FIN "sortaret.in"
  4. #define FOUT "sortaret.out"
  5. #define MAX 500001
  6.  
  7. struct Node {
  8.  
  9. int info;
  10. struct Node *next;
  11. };
  12.  
  13. int num_nodes, num_edges, visited[MAX];
  14.  
  15. struct Node *G[ MAX ], *head = NULL;
  16.  
  17. void dfs(int node) {
  18.  
  19. struct Node *c, *p;
  20.  
  21. visited[ node ] = 1;
  22.  
  23. for(c = G[node]; c; c=c->next) {
  24.  
  25. if(!visited[c->info]) {
  26.  
  27. dfs(c->info);
  28. }
  29. }
  30.  
  31. p = (struct Node*)malloc(sizeof(struct Node));
  32. p->info = node;
  33. p->next = head;
  34. head = p;
  35. }
  36.  
  37. int main(int argc, char const *argv[]) {
  38.  
  39. int i, j;
  40. struct Node *c;
  41.  
  42. //freopen(FIN, "r", stdin);
  43.  
  44. //freopen(FOUT, "w", stdout);
  45.  
  46. scanf("%d %d", &num_nodes, &num_edges);
  47.  
  48. while(num_edges--) {
  49.  
  50. scanf("%d %d", &i, &j);
  51. c = (struct Node*)malloc(sizeof(struct Node));
  52. c->info = j;
  53. c->next = G[ i ];
  54. G[ i ] = c;
  55. }
  56.  
  57. for(int node = 1; node <= num_nodes; ++node) {
  58.  
  59. if(!visited[node]) {
  60.  
  61. dfs(node);
  62. }
  63. }
  64.  
  65. for(c = head; c; c = c->next) {
  66.  
  67. printf("%d ", c->info);
  68. }
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0s 5592KB
stdin
9 8
1 2
1 3
3 4
3 5
5 9
4 6
4 7
4 8
stdout
1 2 3 4 6 7 8 5 9