/*
启发式搜索就是 评估函数 防止拓展不必要的 分支
选:直接加入res + dfs
不选:若后面最好的都 无法 > ans pass 反之 就继续搜索
*/
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
//#include<queue>
//#include<vector>
//#include<bits/stdc++.h>
#define ll long long
#define ddd printf("-----------------------\n");
using namespace std;
const int maxn=1e3+10;
const int inf=0x3f3f3f3f;
struct node{
int w,val;
double bi;
}a[maxn];
int t,m,ans;
bool cmp(node a,node b){
return a.bi>b.bi;
}
double pduan(int pos,int lim){// double /int ok
int tot=0;
for(int i=pos+1;i<=m;i++)
{
if(a[i].w<=lim) lim-=a[i].w,tot+=a[i].val;
else return tot+lim*a[i].bi;
}
return tot;
}
void dfs(int pos,int lim,int res){
if(res>ans) ans=res;
if(pos>m) return;
if(pduan(pos,lim)+res>ans) dfs(pos+1,lim,res);
if(a[pos].w<=lim) dfs(pos+1,lim-a[pos].w,res+a[pos].val);
}
int main()
{
ios::sync_with_stdio(false);
cin>>t>>m;
for(int i=1;i<=m;i++) cin>>a[i].w>>a[i].val,a[i].bi=1.0*a[i].val/a[i].w;
sort(a+1,a+1+m,cmp);
dfs(1,t,0);
cout<<ans<<'\n';
return 0;
}
/*
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
//#include<queue>
//#include<vector>
//#include<bits/stdc++.h>
#define ll long long
#define ddd printf("-----------------------\n");
using namespace std;
const int maxn=1e2+10 ;
const int inf=0x3f3f3f3f;
const int mod=2003;
int t,m,w[maxn],val[maxn],dp[maxn*maxn];
int main()
{
ios::sync_with_stdio(false);
cin>>t>>m;
for(int i=1;i<=m;i++) cin>>w[i]>>val[i];
for(int i=1;i<=m;i++){
for(int j=t;j>=0;j--)
if(j>=w[i])
dp[j]=max(dp[j],dp[j-w[i]]+val[i]);
}
cout<<dp[t]<<'\n';
return 0;
}
*/