#include <iostream>
#include <string>
using namespace std;
struct product{
int weight;
int value;
string name;
};
int main()
{
int maxweight, n;
cin >> maxweight >> n;
int table[maxweight + 1][n + 1],fromwhere[maxweight + 1][n + 1];
product A[n];
for (int i = 0;i < n;i ++)
{
cin >> A[i].name >> A[i].weight >> A[i].value;
}
for (int x = 0;x < maxweight + 1;x ++)
{
table[x][0] = 0;
}
for (int y = 0;y < maxweight + 1;y ++)
{
table[0][y] = 0;
}
for (int y = 1;y < n + 1;y ++)
{
for (int x = 1;x < maxweight + 1;x ++)
{
if (A[y - 1].weight > x)
{
table[x][y] = table[x][y - 1];
fromwhere[x][y] = x;
}
else
{
if(table[x][y - 1] > A[y - 1].value + table[x - A[y - 1].weight][y - 1])
{
//cout << table[x][y - 1] << " " << A[y - 1].value + table[x - A[y - 1].weight][y] << endl;
table[x][y] = table[x][y - 1];
fromwhere[x][y] = x;
}
else
{
table[x][y] = A[y - 1].value + table[x - A[y - 1].weight][y - 1];
fromwhere[x][y] = x - A[y - 1].weight;
}
}
}
}
int maxnum = table[0][n], index = 0;
for (int i = 0;i < maxweight + 1;i ++)
{
//cout << table[i][n]
if(table[i][n] >= maxnum)
{
index = i;
maxnum = table[i][n];
}
}
cout << maxnum << endl;
int c = index;
for (int y = n ;table[c][y] != 0;y --)
{
//cout << " " << table[c][y] << " " << table[c][y - 1];
if (table[c][y] != table[c][y - 1])
{
//cout << c << " ";
cout << A[y - 1].name << endl;
c = fromwhere[c][y];
}
else
{
c = fromwhere[c][y];
}
}
return 0;
}