loop do
  w = gets.to_i
  @num ||= 1
  break if w==0
  n = gets.to_i
  dp = Array.new(n+1){ Array.new(w+1){ {v: 0, w: 0}}}
  n.times.map{ gets.split(",").map(&:to_i) }.each_with_index do |(vi,wi), i|
    w.times do |j|
      t = dp[i][[j+1-wi,0].max]
      dp[i+1][j+1] = if j+1>wi && t[:v]+vi > dp[i][j+1][:v]
        {v: t[:v]+vi, w: t[:w]+wi}
      else
        dp[i][j+1]
      end
    end
  end
  puts "Case #{@num}"
  puts dp[n][w][:v]
  puts dp[n][w][:w]
  @num += 1
end