V1, V2, V3, V4, N = gets.split.map(&:to_i) cap = [V1, V2, V3, V4] V = [V1, 0, 0, 0, 0] E = Hash.new head = [] N.times do |i| head << V.dup break if E[V] idx = i % 4 n_idx = (idx + 1) % 4 u = V.dup r = [V[idx], cap[n_idx] - V[n_idx]].min V[idx] -= r V[n_idx] += r V[-1] = (V[-1] + 1) % 4 E[u] = V.dup end if N < head.size puts head[N][..-2].join(' ') else n = N n -= (head.size - 1) last = head.pop r_idx = head.rindex(last) lp = head[r_idx..-1] ls = lp.size idx = n % ls puts lp[idx][..-2].join(' ') end