#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:640000000")
using namespace std;
const double eps = 1e-9;
const double pi = acos(-1.0);
const int maxn = 4004;
int c[maxn], h[maxn], t[maxn];
int knap[maxn][maxn];
int fre = 0;
int res[20002];
int main() {
  int n, p;
  cin >> n >> p;
  vector<pair<pair<int, int>, int> > v;
  for (int i = 0; i < n; i++) {
    scanf("%d%d%d", &c[i], &h[i], &t[i]);
    v.push_back(make_pair(make_pair(t[i], 0), i));
    v.push_back(make_pair(make_pair(t[i] + p, 1), i));
  }
  int q;
  cin >> q;
  for (int i = 0; i < q; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    v.push_back(make_pair(make_pair(a, 2 + i), b));
  }
  sort((v).begin(), (v).end());
  stack<pair<int, int> > st1, st2;
  sort((v).begin(), (v).end());
  for (int i = 0; i < (int)(v).size(); i++) {
    if (v[i].first.second == 0) {
      int id = v[i].second;
      if (st1.empty()) {
        for (int j = c[id]; j < maxn; j++) {
          knap[fre][j] = h[id];
        }
      } else {
        int e = st1.top().first;
        for (int j = 0; j < maxn; j++) {
          knap[fre][j] = knap[e][j];
        }
        for (int j = c[id]; j < maxn; j++) {
          knap[fre][j] = max(knap[fre][j], knap[e][j - c[id]] + h[id]);
        }
      }
      st1.push(make_pair(fre, id));
      fre++;
    } else if (v[i].first.second == 1) {
      if (st2.empty()) {
        while (!st1.empty()) {
          int val = st1.top().first;
          int id = st1.top().second;
          st1.pop();
          if (st2.empty()) {
            memset(knap[val], 0, sizeof(knap[val]));
            for (int j = c[id]; j < maxn; j++) {
              knap[val][j] = h[id];
            }
          } else {
            int e = st2.top().first;
            for (int j = 0; j < maxn; j++) {
              knap[val][j] = knap[e][j];
            }
            for (int j = c[id]; j < maxn; j++) {
              knap[val][j] = max(knap[val][j], knap[e][j - c[id]] + h[id]);
            }
          }
          st2.push(make_pair(val, id));
        }
      }
      st2.pop();
    } else {
      if (st1.empty() && st2.empty()) {
        res[v[i].first.second - 2] = 0;
      } else if (!st1.empty() && !st2.empty()) {
        int ans = 0;
        for (int j = 0; j <= v[i].second; j++) {
          ans = max(ans, knap[st1.top().first][v[i].second - j] +
                             knap[st2.top().first][j]);
        }
        res[v[i].first.second - 2] = ans;
      } else if (st1.empty()) {
        res[v[i].first.second - 2] = knap[st2.top().first][v[i].second];
      } else {
        res[v[i].first.second - 2] = knap[st1.top().first][v[i].second];
      }
    }
  }
  for (int i = 0; i < q; i++) {
    printf("%d\n", res[i]);
  }
  return 0;
}
