let () =
  let shift (c0,c1,c2,c3,c4,c5,c6,c7)
    = (c7,c0,c1,c2,c3,c4,c5,c6) and
      get_int (c0,c1,c2,c3,c4,c5,c6,c7) =
      c0*10000000+c1*1000000+c2*100000+c3*10000+c4*1000+c5*100+c6*10+c7 and
      to_tuple = fun s t u v w x y z -> (s,t,u,v,w,x,y,z) and
      f x y = if y > x then y-x else 0
  in
  let rec read () =
    try let (p0,p1,p2,p3,p4,p5,p6,p7) =
          Scanf.scanf " %d %d %d %d %d %d %d %d\n" to_tuple in
        let c = (4,1,4,1,2,1,2,1) and
            diff (c0,c1,c2,c3,c4,c5,c6,c7) =
              (f c0 p0)+(f c1 p1)+(f c2 p2)+(f c3 p3)+(f c4 p4)+(f c5 p5)+(f c6 p6)+(f c7 p7)
        in
        let rec loop c min_c min n  = function
            0 -> min_c
          | i ->
             print_endline (string_of_int (diff c));
             let intc = get_int c in
             if (diff c) <= min && intc < n then
                 loop (shift c) c (diff c) intc (i-1)
             else
               loop (shift c) min_c min n (i-1)
        in
        let (c0,c1,c2,c3,c4,c5,c6,c7) = loop  c c 99999999 99999999 8 in
        Printf.printf "%d %d %d %d %d %d %d %d\n" c0 c1 c2 c3 c4 c5 c6 c7
        ;read ()
    with
      End_of_file -> ()
  in read ()
;;