fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. #define MAXV 10005
  5. #define MAXE 200005
  6.  
  7. int head[MAXV];
  8. int to[MAXE];
  9. int next_edge[MAXE];
  10. int edge_id[MAXE];
  11. int edge_count = 0;
  12.  
  13. bool used_edge[MAXE / 2];
  14. int degree[MAXV];
  15. int circuit[MAXE];
  16. int circuit_size = 0;
  17.  
  18. void add_edge(int u, int v, int id) {
  19. to[edge_count] = v;
  20. edge_id[edge_count] = id;
  21. next_edge[edge_count] = head[u];
  22. head[u] = edge_count++;
  23. degree[u]++;
  24. }
  25.  
  26. void find_circuit(int u) {
  27. while (head[u] != -1) {
  28. int i = head[u];
  29. head[u] = next_edge[i];
  30.  
  31. int id = edge_id[i];
  32. if (used_edge[id]) continue;
  33.  
  34. used_edge[id] = true;
  35. find_circuit(to[i]);
  36. }
  37. circuit[circuit_size++] = u;
  38. }
  39.  
  40. int main() {
  41. int n, m;
  42. printf("Nhap so dinh va so canh: ");
  43. if (scanf("%d %d", &n, &m) != 2) return 0;
  44.  
  45. for (int i = 0; i < n; i++) {
  46. head[i] = -1;
  47. degree[i] = 0;
  48. }
  49.  
  50. printf("Nhap cac canh (u v):\n");
  51. for (int i = 0; i < m; i++) {
  52. int u, v;
  53. scanf("%d %d", &u, &v);
  54. add_edge(u, v, i);
  55. add_edge(v, u, i);
  56. }
  57.  
  58. int start_node = -1;
  59. for (int i = 0; i < n; i++) {
  60. if (degree[i] % 2 != 0) {
  61. printf("Khong co chu trinh Euler).\n", i);
  62. return 0;
  63. }
  64. if (degree[i] > 0 && start_node == -1) start_node = i;
  65. }
  66.  
  67. if (m > 0 && start_node == -1) return 0;
  68. if (m == 0) { printf("0\n"); return 0; }
  69.  
  70. find_circuit(start_node);
  71.  
  72. if (circuit_size != m + 1) {
  73. printf("Do thi khong lien thong.\n");
  74. } else {
  75. printf("Chu trinh Euler: ");
  76. for (int i = circuit_size - 1; i >= 0; i--) {
  77. printf("%d%s", circuit[i], (i == 0 ? "" : " -> "));
  78. }
  79. printf("\n");
  80. }
  81.  
  82. return 0;
  83. }
  84.  
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Nhap so dinh va so canh: