
//============================================================================
// Name        : AOJ0042.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

#define MAX_N 1000
#define MAX_M 10000

int n, W;
short w[MAX_N] = { 0 }, v[MAX_N] = { 0 };

int dp[MAX_N + 1][MAX_M + 1] = { 0 };

void solve() {

  for (int i = n - 1; i >= 0; i--) {
    for (int j = 0; j <= W; j++) {
      if (j < w[i]) {
        dp[i][j] = dp[i + 1][j];
      } else {
        dp[i][j] = max(dp[i + 1][j], dp[i + 1][j - w[i]] + v[i]);

      }
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j <= W; j++) {
      //printf("%5d", dp[i][j]);
    }
    //cout << endl;
  }
  //cout << endl;
  cout << dp[0][W] << endl;
  int i;
  for (i = W; i >= 0; i--) {
    if (dp[0][W] != dp[0][i]) break;
  }
  cout << i + 1 << endl;

}

int main() {

  int kase = 1;
  char str[11];
  cin >> W;

  while (W != 0) {
    cin >> n;

    for (int i = 0; i < n; i++) {
      cin >> str;

      int j = 0;

      v[i] = 0;
      w[i] = 0;

      while (str[j] != ',') {
        v[i] = v[i] * 10;
        v[i] = v[i] + (str[j] - '0');
        j++;
      }

      j++;

      while (str[j] != '\0') {
        w[i] = w[i] * 10;
        w[i] = w[i] + (str[j] - '0');
        j++;
      }
    }
    /*
     for (int i = 0; i < n; i++) {
     cout << v[i] << endl;
     cout << w[i] << endl;
     }
     */
    cout << "Case " << kase << ":" << endl;
    solve();

    kase++;
    cin >> W;
  }

  return 0;
}