RT
#include<bits/stdc++.h>
#define INF (1<<30)
using namespace std;
int t2;
inline void incntime()
{
int x1,y1,x2,y2,on,tw;
scanf("%d:%d %d:%d ",&x1,&y1,&x2,&y2);
on=x1*60+y1;
tw=x2*60+y2;
t2=tw-on;
}
int n,t[10008],c[10008],p[10008],t1[1000003],c1[1000003],n2,f[10000008];
void binary()
{
for(int i=1;i<=n;i++)
{
int a=1;
while(p[i]!=0)
{
t1[++n2]=t[i]*a;
c1[n2]=c[i]*a;
p[i]-=a;
a<<=1;
if(p[i]<a)
{
t1[++n2]=t[i]*p[i];
c1[n2]=c[i]*p[i];
p[i]=0;
}
}
}
}
int main()
{
incntime();
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>t[i]>>c[i]>>p[i];
if(p[i]==0) p[i]=INF;
}
binary();
for(int i=1;i<=n2;i++)
{
for(int j=t2;j>=t1[i];j--)
{
f[j]=max(f[j],f[j-t1[i]]+c1[i]);
}
}
cout<<f[t2];
return 0;
}