def f(n, s, a) latter_a = a.dup first_a = latter_a.shift(n/2) g = lambda{|i, sum, a, rr, h| h[sum] ||= [] h[sum] << rr (i...a.size).each{|ii| g.(ii + 1, sum + a[ii], a, rr + [ii], h) } h } firsts = g.(0, 0, first_a, [], {}) latters = g.(0, 0, latter_a, [], {}) r = [] firsts.each{|f_sum, f_a| if latters.key?(s - f_sum) l_a = latters[s - f_sum].map{|a| a.map{|i|first_a.size + i}} f_a.product(l_a).each{|a| r << a.flatten } end } # p [first_a, latter_a] # p [firsts, latters] r.map{|v|v.map(&:succ)}.sort end N, S = gets.split.map(&:to_i) P = N.times.map{gets.to_i} f(N, S, P).each{|a| puts a * " " }