1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <bits/stdc++.h>
#define REP(i,n) for (int _n=(n), i=0;i<_n;++i)
#define FOR(i,a,b) for (int i=(a),_b=(b);i<=_b;++i)
#define FORD(i,a,b) for (int i=(a),_b=(b);i>=_b;--i)
#define TRACE(x) std::cerr << "TRACE(" #x ")" << std::endl;
#define DEBUG(x) std::cerr << #x << " = " << (x) << std::endl;

void init_io() {
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
}

using State = std::array<int, 3>;

State size;
State initial;

int num_states;
std::vector<int> solution;

void read_input() {
  REP(i, 3) std::cin >> size[i];
  REP(i, 3) std::cin >> initial[i];
}

void prepare_encoding() {
  num_states = 1;
  REP(i, 3) num_states += 2 * (size[i] + 1);
}

int encode(const State &state) {
  int special = 0;
  int next = 1;
  int encoded = 1;
  while (special != 3 && state[special] != 0 && state[special] != size[special]) {
    encoded += 2 * (size[next] + 1);
    ++special;
    ++next;
    if (next==3) next = 0;
  }
  if (special == 3) return 0;
  if (state[special] != 0) encoded += (size[next] + 1);
  encoded += state[next];
  return encoded;
}

State make_move(State s, int from, int to) {
  const int amount = std::min(s[from], size[to] - s[to]);
  s[from] -= amount;
  s[to] += amount;
  return s;
}

void bfs() {
  solution.assign(size[2] + 1, -1);
  std::vector<char> visited(num_states, 0);
  std::vector<State> current;
  std::vector<State> next;
  current.reserve(num_states);
  next.reserve(num_states);

  current.push_back(initial);
  visited[encode(initial)] = 1;
  int dist = 0;
  for (;;) {
    if (current.empty()) {
      current.swap(next);
      ++dist;
      if (current.empty()) break;
    }
    const State state = current.back();
    current.pop_back();
    REP(i, 3) {
      int &s = solution[state[i]];
      if (s==-1) s=dist;
    }
    REP(from, 3) REP(to, 3) if (from != to) {
      const State state2 = make_move(state, from, to);
      auto &vis = visited[encode(state2)];
      if (vis) continue;
      vis = 1;
      next.push_back(state2);
    }
  }
}

void print() {
  for (int s : solution) std::cout << s << ' ';
  std::cout << '\n';
}

int main() {
  init_io();
  read_input();
  prepare_encoding();
  bfs();
  print();
}