附件背包
#include <iostream>
#include <cstdio>
using namespace std;
int read()
{
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=x*10+c-'0';
c=getchar();
}
return f*x;
}
const int M=35000,N=1000;
int n,W,f[M],v[N],w[N],co[N],son[N][10],w1,v1,q,col,p[N],ans;
int main()
{
W=read(); n=read();
for(int i=1;i<=n;i++)
{
w1=read(); v1=read()*w1; q=read();
if(!q)
{
col++;
son[col][++p[col]]=i;
co[i]=col;
w[i]=w1; v[i]=v1;
}
else
{
son[co[q]][++p[co[q]]]=i;
co[i]=co[q];
w[i]=w[q]+w1;
v[i]=v[q]+v1;
if(p[co[q]]==3)
{
son[co[q]][++p[co[q]]]=n+i;
co[n+i]=co[q];
w[n+i]=w[son[co[q]][2]]+w[son[co[q]][3]]-w[q];
v[n+i]=v[son[co[q]][2]]+v[son[co[q]][3]]-v[q];
}
}
}
for(int i=1;i<=col;i++)
for(int j=W;j+1;j--)
for(int k=1;k<=4;k++)
{
if(j<w[son[i][k]]) continue;
f[j]=max(f[j],f[j-w[son[i][k]]]+v[son[i][k]]);
}
for(int i=1;i<=W;i++) ans=max(ans,f[i]);
cout<<ans;
return 0;
}