record Subset, sum : Int32, indices : Array(Int32) def solve(m) p = Array.new(m) { gets.not_nil!.to_i } res = [] of Subset (0...(1 << m)).each do |bit| sum = 0 indices = [] of Int32 m.times do |i| if (bit >> i) & 1 == 1 sum += p[i] indices << i end end res << Subset.new(sum, indices) end res end n, s = gets.not_nil!.split.map(&.to_i) half = n // 2 p1 = solve(half) p2 = solve(n - half) # Use a hash for O(1) lookups p2_map = Hash(Int32, Array(Array(Int32))).new { |h, k| h[k] = [] of Array(Int32) } p2.each do |subset| p2_map[subset.sum] << subset.indices end ans = [] of Array(Int32) p1.each do |subset1| target = s - subset1.sum next unless p2_map.has_key?(target) p2_map[target].each do |indices2| combined = subset1.indices.dup indices2.each { |x| combined << x + half } ans << combined end end # Sort and output ans.sort.each do |indices| puts indices.map { |x| x + 1 }.join(" ") end