#include<stdio.h>
int i, j, k, n, m, c, sum = 0, save = 1;
int x, y, z;
int arr[100001][4] = {};
void change()
{
x = arr[j][1];
y = arr[j][2];
z = arr[j][3];
arr[j][1] = arr[j + 1][1];
arr[j][2] = arr[j + 1][2];
arr[j][3] = arr[j + 1][3];
arr[j + 1][1] = x;
arr[j + 1][2] = y;
arr[j + 1][3] = z;
}
int main()
{
scanf("%d %d %d", &n, &c, &m);
for (i = 1 ; i <= m ; i ++)
{
scanf("%d %d %d", &arr[i][1], &arr[i][2], &arr[i][3]);
}
for (i = 1 ; i < m ; i ++)
{
for (j = 1 ; j <= m - i ; j ++)
{
if (arr[j][1] > arr[j + 1][1])
{
change();
}
else if (arr[j][1] == arr[j + 1][1] && arr[j][2] > arr[j + 1][2])
{
change();
}
}
}
for (i = 1 ; i <= m ; i ++)
{
for (j = 1 ; ; j ++)
{
if (sum + arr[i][3] <= c)
{
sum += arr[i][3];
}
else
{
break;
}
}
}
for (i = 1 ; i <= n ; i ++)
{
for (j = save ; j <= m ; j ++)
{
if (j != 1 && arr[j - 1][1] != arr[j][1] || sum == c)
{
save = j + 1;
break;
}
if (sum + arr[j][3] <= c)
{
sum += arr[j][3];
}
else if (sum < c)
{
sum = c;
}
}
}
return 0;
}