fork(1) download
  1. /*
  2.   Copyright 2011 Marek "p2004a" Rusinowski
  3.   Finding Hamilton cycle
  4. */
  5. #include <cstdio>
  6. #include <vector>
  7. #include <stack>
  8.  
  9. #define MAXN 1000
  10.  
  11. std::vector<int> edges[MAXN];
  12. std::stack<int> cycle;
  13. bool visited[MAXN];
  14. int n, m;
  15.  
  16. bool dfs(int v) {
  17. visited[v] = true;
  18. cycle.push(v);
  19. for (unsigned i = 0; i < edges[v].size(); ++i) {
  20. if (edges[v][i] == 0 && (int)cycle.size() == n) {
  21. return true;
  22. }
  23. if (!visited[edges[v][i]]) {
  24. if (dfs(edges[v][i])) {
  25. return true;
  26. }
  27. }
  28. }
  29. visited[v] = false;
  30. cycle.pop();
  31. return false;
  32. }
  33.  
  34. int main() {
  35. int a, b;
  36. scanf("%d %d", &n, &m);
  37. for (int i = 0; i < m; ++i) {
  38. scanf("%d %d", &a, &b);
  39. edges[--a].push_back(--b);
  40. edges[b].push_back(a);
  41. }
  42. if (dfs(0)) {
  43. while (!cycle.empty()) {
  44. printf("%d ", cycle.top() + 1);
  45. cycle.pop();
  46. }
  47. printf("\n");
  48. } else {
  49. printf("false\n");
  50. }
  51. return 0;
  52. }
  53.  
stdin
5 5
1 2
2 3
3 4
4 5
5 1
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:34: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
prog.cpp:36: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
stdout
5 4 3 2 1