c=1

while 1:

    W=int(eval(input()))

    if W==0:break

    n=int(eval(input()))

    dp=[0]*(W+1)

    for i in range(n):

        v,w = list(map(int, input().split(',')))

        for j in range(W,w-1,-1):

            dp[j]=max(dp[j-w]+v,dp[j])

    for i in range(W+1):

        if dp[W]==dp[i]:break

    print(('Case %d:\n%d\n%d'%(c,dp[W],i)))

    c+=1
c=1

while 1:

    W=int(eval(input()))

    if W==0:break

    dp=[0]*(W+1)

    for i in range(int(eval(input()))):

        v,w=list(map(int, input().split(',')))

        for j in range(W,w-1,-1):

            if dp[j]<dp[j-w]+v:dp[j]=dp[j-w]+v

    for i in range(W+1):

        if dp[W]==dp[i]:break

    print(('Case %d:\n%d\n%d'%(c,dp[W],i)))

    c+=1
c = 1
while 1:
    W = int(eval(input()))
    if W == 0:
        break
    n = int(eval(input()))
    dp = [0] * (W + 1)
    for i in range(n):
        v, w = list(map(int, input().split(",")))
        for j in range(W, w - 1, -1):
            dp[j] = max(dp[j - w] + v, dp[j])
    for i in range(W + 1):
        if dp[W] == dp[i]:
            break
    print(("Case %d:\n%d\n%d" % (c, dp[W], i)))
    c += 1

c = 1
while 1:
    W = int(eval(input()))
    if W == 0:
        break
    dp = [0] * (W + 1)
    for i in range(int(eval(input()))):
        v, w = list(map(int, input().split(",")))
        for j in range(W, w - 1, -1):
            if dp[j] < dp[j - w] + v:
                dp[j] = dp[j - w] + v
    for i in range(W + 1):
        if dp[W] == dp[i]:
            break
    print(("Case %d:\n%d\n%d" % (c, dp[W], i)))
    c += 1

-    n = int(eval(input())) -    for i in range(n): +    for i in range(int(eval(input()))): -            dp[j] = max(dp[j - w] + v, dp[j]) +            if dp[j] < dp[j - w] + v: +                dp[j] = dp[j - w] + v