#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<string>
#include<sstream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cctype>
#include<climits>
using namespace std;
#define REP(i, j) for(int i = 0; i < j; i++)
#define FOR(i, j, k) for(int i = j; i < k; i++)
#define P pair<int, int>
const int INF = INT_MAX / 2;

int main(){
    int w;
    while(cin >>w && w){
        int n;
        cin >>n;
        vector< vector<int> > dp(n + 1, vector<int>(w + 1));
        REP(i, dp.size()){
            REP(j, dp[i].size()){
                dp[i][j] = 0;
            }
        }
        dp[0][0] = 0;
        //input begin
        vector<P> j(n + 1);
        string str;
        getline(cin, str);
        FOR(i, 1, n + 1){
            getline(cin, str);
            stringstream ss(str);
            int a, b;
            char c;
            ss >>a >>c >>b;
            j[i].first = a;
            j[i].second = b;
        }
        //input end

        FOR(i, 1, dp.size()){
            int value = j[i].first, weight = j[i].second;
            REP(j, dp[i].size()){
                if(j >= weight && j - weight >= 0){
                    dp[i][j] = max(dp[i][j], dp[i - 1][j - weight] + value);
                } else{
                    dp[i][j] = max(dp[i][j], dp[i - 1][j]);
                }
            }
        }

        int ans = -1;
        REP(i, dp[0].size()){
            if(dp[n][i] > ans){
                ans = dp[n][i];
            }
        }
        cout <<ans <<endl;
    }
    return 0;
}