#include <bits/stdc++.h>
using namespace std;
string ts,te;
int n,w;
int v[10005],m[10005];
int f[1005];
int main()
{
cin>>ts>>te>>n;
int s = 0,e = 0;
if(ts[1] == ':')
s = (ts[0] - '0') * 60 + (ts[2] - '0') * 10 + ts[3] - '0';
else s = ((ts[0] - '0') * 10 + ts[1] - '0') * 60 + (ts[3] - '0') * 10 + ts[4] - '0';
if(te[1] == ':')
e = (te[0] - '0') * 60 + (te[2] - '0') * 10 + te[3] - '0';
else e = ((te[0] - '0') * 10 + te[1] - '0') * 60 + (te[3] - '0') * 10 + te[4] - '0';
w = e - s;
int cnt = 0;
for(int i = 1;i <= n;i ++)
{
int a,b,c;
cin>>a>>b>>c;
if(!c)c = 1005;
for(int k = 1;k <= c;k *= 2)
{
m[++cnt] = a * k;
v[cnt] = b * k;
c -= k;
}
if(c)
{
m[++cnt] = a * c;
v[cnt] = b * c;
}
}
for(int i = 1;i <= cnt;i ++)
for(int j = w;j >= m[i];j --)
f[j] = max(f[j],f[j - m[i]] + v[i]);
cout<<f[w]<<'\n';
return 0;
}