Go: package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

const MaxW = 1000
const MaxN = 1000

type Tuple struct {
	Value  int
	Weight int
}

func nextLine(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func solve(w int, n int, vws []Tuple) Tuple {
	var dp [MaxN + 1][MaxW + 1]int

	for i := 0; i < n; i++ {
		for j:= w; j > 0; j-- {
			if j < vws[i].Weight {
				dp[i + 1][j] = dp[i][j]
			} else {
				dp[i + 1][j] = int(math.Max(float64(dp[i][j]), float64(dp[i][j - vws[i].Weight] + vws[i].Value)))
			}
		}
	}

	maxValue := dp[n][w]
	minWeight := w

	for j := w - 1; j > 0; j-- {
		if maxValue == dp[n][j] {
			minWeight = j
		} else {
			break
		}
	}

	return Tuple{Value: maxValue, Weight: minWeight}
}

func main() {
	var sc = bufio.NewScanner(os.Stdin)
	index := 1
	for {
		var w, n int
		w, _ = strconv.Atoi(nextLine(sc))
		if w == 0 {
			return
		}
		n, _ = strconv.Atoi(nextLine(sc))

		vws := make([]Tuple, n, n)
		for i := 0; i < n; i++ {
			array := strings.Split(nextLine(sc), ",")
			v, _ := strconv.Atoi(array[0])
			w, _ := strconv.Atoi(array[1])
			vws[i] = Tuple{Value: v, Weight: w}
		}

		t := solve(w, n, vws)
		fmt.Printf("Case %d:\n", index)
		fmt.Println(t.Value)
		fmt.Println(t.Weight)
		index++
	}
}

Python: count = 0

while True:
    count += 1
    W = int(input())
    if W == 0:
        break
    N = int(input())
    value = []
    weight = []
    for i in range(N):
        a, b = map(int, input().split())
        value.append(a)
        weight.append(b)
    dp = [[-float("inf") for i in range(W+1)] for j in range(N+1)]
    for i in range(W+1):
        dp[0][i] = 0
        
    for i in range(N):
        for w in range(W+1):
            if w >= weight[i]:
                dp[i+1][w] = max(dp[i][w-weight[i]]+value[i], dp[i][w])
            else:
                dp[i+1][w] = dp[i][w]
    print("Case {0}:\n{1}\n{2}".format(count, dp[N][W], dp[N].index(dp[N][W])))

Python: # ナップサック問題を python で解く
case = 0
while True:
    case += 1
    w = int(input())
    if w == 0:
        break
    n = int(input())
    item = []
    for i in range(n):
        item.append(tuple(map(int, input().split(","))))

    dp = [ [0 for j in range(w + 1)] for i in range(n + 1) ]
    for i in range(n):
        for j in range(w + 1):
            value  = item[i][0]
            weight = item[i][1]
            # dp[i][j] : 0..i番目の荷物、重さ j 以下の最大の価値
            if j - weight >= 0 and dp[i+1][j - weight] == dp[i][j - weight]:
                dp[i+1][j] = max(dp[i][j], dp[i+1][j - weight] + value)
            else:
                dp[i+1][j] = max(dp[i][j], dp[i+1][j-1])

    for j in range(w + 1):
        if dp[n][j] == dp[n][w]:
            max_w = j
            break

    print("Case {0}:".format(case))
    print(dp[n][w])
    print(max_w)

Python: import itertools

def solve():
    cache = {}
    def loop(i, w):
        if (i, w) in cache:
            return cache[i, w]
        if i == N:
            return (0, 0)
        cache[i, w] = loop(i + 1, w)
        if v[i][1] <= w:
            t = loop(i + 1, w - v[i][1])
            cache[i, w] = max(cache[i, w], (t[0] + v[i][0], t[1] + v[i][1]), key=lambda u: u[0])
        return cache[i, w]
    return loop(0, W)

for dn in itertools.count(1):
    W = int(input())
    if W == 0: break
    N = int(input())
    v = [tuple(map(int, input().split(','))) for _ in range(N)]
    optim = solve()
    print("Case %d:\n%d\n%d" % (dn, optim[0], optim[1]))

Python: import itertools

case = 0
while True:
    case += 1
    w_max = int(input())
    if w_max == 0:
        break
    n = int(input())
    t = []
    for i in range(n):
        t.append(list(map(int, input().split(","))))
    v_best = 0
    w_best = 0
    p_all = itertools.product([0,1], repeat=n)
    for p in p_all:
        v = 0
        w = 0
        for i in range(n):
            v += p[i]*t[i][0]
            w += p[i]*t[i][1]
        if v > v_best and w <= w_max:
            v_best = v
            w_best = w
        elif v == v_best and w < w_best:
            v_best = v
            w_best = w
    print("Case ",case,":",sep="")
    print(v_best)
    print(w_best)

Python: count=1
while True:
    vw=[[0,0]]
    W=int(input())
    if W==0:
        break
    n=int(input())
    for i in range(n):
        vw.append(list(map(int,input().split(','))))
    
    dp=[]
    weight=[]
    
    for _ in range(n+1):
        dp.append([0 for i in range(W+1)])
        weight.append([0 for i in range(W+1)])
    for i in range(1,n+1):
        for j in range(0,W-vw[i][1]+1):
            dp[i][j+vw[i][1]]=max(dp[i-1][j+vw[i][1]],dp[i-1][j]+vw[i][0])
            if dp[i][j+vw[i][1]]==dp[i-1][j]+vw[i][0]:
                weight[i][j+vw[i][1]]=weight[i-1][j]+vw[i][1]
            else:
                weight[i][j+vw[i][1]]=weight[i-1][j]
            
    print('Case '+'{}'.format(count)+':')
    print(dp[n][W])
    print(weight[n][W])
    count+=1

Python: #coding:utf-8

from __future__ import division, print_function
try:
    input = raw_input
    range = xrange
except NameError:
    pass


def solve(W, N, treasures):
    dp = [0] + [-1] * W
    for v, w in treasures:
        for j in range(W, w - 1, -1):
            if dp[j - w] >= 0:
                dp[j] = max(dp[j], dp[j - w] + v)

    ans = max(dp)
    return ans, dp.index(ans)

cnt = 1
while True:
    W = int(input())
    if W == 0:
        break
    N = int(input())
    
    treasures = [tuple(map(int, input().split(','))) for _ in range(N)]
    (v, w) = solve(W, N, treasures)
    print('Case %d:\n%d\n%d' % (cnt, v, w))
    cnt += 1

Python: # Aizu Problem 0042: A Thief
#
import sys, math, os

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")


def knapsack(n, v, w, W):
    #
    # 0/1 knapsack implementation
    #
    # Input:
    #    Values (stored in array v)
    #    Weights (stored in array w)
    #    Number of distinct items (n)
    #    Knapsack capacity (W)
    #
    m = [[0 for _ in range(W + 1)] for __ in range(N + 1)]
    for i in range(1, N + 1):
        for j in range(W + 1):
            if w[i - 1] > j:
                m[i][j] = m[i-1][j]
            else:
                m[i][j] = max(m[i-1][j], m[i-1][j-w[i - 1]] + v[i - 1])
    print(m)
    return m[N][W]

def total_value(items, max_weight):
    return  sum([x[2] for x in items]) if sum([x[1] for x in items]) < max_weight else 0
 
cache = {}
def solve(items, max_weight):
    if not items:
        return ()
    if (items,max_weight) not in cache:
        head = items[0]
        tail = items[1:]
        include = (head,) + solve(tail, max_weight - head[1])
        dont_include = solve(tail, max_weight)
        if total_value(include, max_weight) > total_value(dont_include, max_weight):
            answer = include
        else:
            answer = dont_include
        cache[(items,max_weight)] = answer
    return cache[(items,max_weight)]

case = 0
while True:
    cache = {}
    W = int(input())
    if W == 0:
        break
    N = int(input())
    items = []
    for n in range(N):
        a, b = [int(_) for _ in input().split(',')]
        items.append(("", b, a))
    items = tuple(items)
    solution = solve(items, W)
    case += 1
    print("Case %d:" % case)
    print(sum([x[2] for x in solution]))
    print(sum([x[1] for x in solution]))

Python: ctr = 1
while True:
    w = int(input())
    if w==0: break
    dp = [0]*(w+1)

    n = int(input())
    for i in range(n):
        vi, wi = map(int, input().split(","))
        for j in range(w,wi-1,-1):
            dp[j] = max(dp[j],dp[j-wi]+vi)

    print("Case "+str(ctr)+":")
    print(max(dp))
    print(dp.index(max(dp)))
    ctr += 1