結果

問題 No.15 カタログショッピング
ユーザー vjudge1
提出日時 2025-09-08 10:31:19
言語 Crystal
(1.14.0)
結果
AC  
実行時間 57 ms / 5,000 ms
コード長 1,154 bytes
コンパイル時間 14,292 ms
コンパイル使用メモリ 317,568 KB
実行使用メモリ 17,920 KB
最終ジャッジ日時 2025-09-08 10:31:34
合計ジャッジ時間 14,017 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 10
権限があれば一括ダウンロードができます

ソースコード

diff #

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)

# Pre-sort and extract just sums for binary search
p2_sorted = p2.sort_by(&.sum)
p2_sums = p2_sorted.map(&.sum)

ans = [] of Array(Int32)
p1.each do |subset1|
  target = s - subset1.sum
  next if target < 0
  
  # Binary search for the range of subsets with target sum
  left_idx = p2_sums.bsearch_index { |x| x >= target }
  next unless left_idx
  
  right_idx = p2_sums.bsearch_index { |x| x > target } || p2_sums.size
  
  (left_idx...right_idx).each do |i|
    subset2 = p2_sorted[i]
    combined = subset1.indices.dup
    subset2.indices.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
0