yeputons

Untitled

Oct 28th, 2014
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.16 KB | None | 0 0
  1. program HamiltonianPath;
  2. {$APPTYPE CONSOLE}
  3.  
  4. const MAXN = 10;
  5.  
  6. var
  7.   n : longint;
  8.   g : array[1..MAXN, 1..MAXN] of boolean;
  9.   ans : array[1..MAXN] of longint;
  10.   was : array[1..MAXN] of boolean;
  11.  
  12. function solve(ver, depth : longint) : boolean;
  13. var
  14.   next : longint;
  15. begin
  16.   was[ver] := true;
  17.   ans[depth] := ver;
  18.  
  19.   if depth = n then begin
  20.     result := true;
  21.     exit;
  22.   end;
  23.  
  24.   for next := 1 to n do if not was[next] and g[ver, next] then begin
  25.     if solve(next, depth + 1) then begin
  26.       result := true;
  27.       exit;
  28.     end;
  29.   end;
  30.  
  31.   was[ver] := false;
  32.   result := false;
  33. end;
  34.  
  35.  
  36. var
  37.   m : longint;
  38.   i, i2 : longint;
  39.   a, b : longint;
  40. begin
  41.   reset(input, 'hamiltonian.in');
  42.   rewrite(output, 'hamiltonian.out');
  43.  
  44.   fillchar(g, sizeof(g), 0);
  45.   read(n, m);
  46.   for i := 1 to m do begin
  47.     read(a, b);
  48.     g[a, b] := true;
  49.     g[b, a] := true;
  50.   end;
  51.  
  52.   fillchar(was, sizeof(was), 0);
  53.   for i := 1 to n do begin
  54.     if solve(i, 1) then begin
  55.       for i2 := 1 to n do begin
  56.         if i2 <> 1 then write(' ');
  57.         write(ans[i2]);
  58.       end;
  59.       writeln;
  60.       exit;
  61.     end;
  62.   end;
  63.  
  64.   writeln('No solution');
  65. end.
Add Comment
Please, Sign In to add comment