#include <bits/stdc++.h>
using namespace std;
const int maxt = 20005;
const int maxb = 4001;
int n, p, q, dp[maxt >> 1][maxb], ans[maxt], dp2[maxb];
vector<pair<int, int> > items[maxt];
vector<pair<int, pair<int, int> > > ask[maxt];
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1, c, h, t; i <= n; i++) {
    scanf("%d%d%d", &c, &h, &t);
    items[t].push_back(make_pair(c, h));
  }
  int maxk = 0;
  scanf("%d", &q);
  for (int i = 1, a, b, k; i <= q; i++) {
    scanf("%d%d", &a, &b);
    ask[max(0, a - p + 1)].push_back(make_pair(a, make_pair(b, i)));
    maxk = max(maxk, a / p);
  }
  for (int k = 0; k <= maxk; k++) {
    int T = k * p;
    for (int i = T; i <= T + p; i++) {
      if (i > 20000) break;
      if (i == T)
        memset(dp[i - T], 0, sizeof dp[i - T]);
      else
        memcpy(dp[i - T], dp[i - 1 - T], sizeof dp[i - T]);
      for (int j = 0; j < (int)items[i].size(); j++)
        for (int z = maxb - 1; z >= items[i][j].first; z--)
          dp[i - T][z] = max(dp[i - T][z], dp[i - T][z - items[i][j].first] +
                                               items[i][j].second);
    }
    for (int i = 0; i < (int)ask[T].size(); i++)
      ans[ask[T][i].second.second] =
          dp[ask[T][i].first - T][ask[T][i].second.first];
    memset(dp2, 0, sizeof(dp2));
    for (int i = T - 1; i >= T - p; i--) {
      if (i < 0) break;
      for (int j = 0; j < (int)items[i].size(); j++)
        for (int z = maxb - 1; z >= items[i][j].first; z--)
          dp2[z] = max(dp2[z], dp2[z - items[i][j].first] + items[i][j].second);
      for (int j = 0; j < (int)ask[i].size(); j++)
        if (ask[i][j].first == T - 1)
          ans[ask[i][j].second.second] = dp2[ask[i][j].second.first];
        else if (ask[i][j].first >= T) {
          int ret = 0;
          for (int z = 0; z <= ask[i][j].second.first; z++)
            ret = max(
                ret,
                dp2[z] + dp[ask[i][j].first - T][ask[i][j].second.first - z]);
          ans[ask[i][j].second.second] = ret;
        }
    }
  }
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
  return 0;
}
