#include <bits/stdc++.h>
using namespace std;
int n;
int p;
struct st {
  int cost;
  int hap;
  int tim;
};
vector<st> v;
bool operator<(const st &a, const st &b) { return a.tim < b.tim; }
int q;
int ans[20012];
set<pair<pair<int, int>, pair<int, int> > > s;
int dp[4012][4002];
inline void solve(int l, int r) {
  if (l > r) return;
  int mid = (l + r) >> 1;
  for (int i = l; i <= r; i++) {
    for (int j = 0; j <= 4000; j++) {
      dp[i][j] = 0;
    }
  }
  dp[mid][v[mid].cost] = v[mid].hap;
  for (int j = 1; j <= 4000; j++) {
    dp[mid][j] = max(dp[mid][j], dp[mid][j - 1]);
  }
  if (mid + 1 <= r) {
    dp[mid + 1][v[mid + 1].cost] = v[mid + 1].hap;
    for (int j = 1; j <= 4000; j++) {
      dp[mid + 1][j] = max(dp[mid + 1][j], dp[mid + 1][j - 1]);
    }
  }
  for (int i = mid + 2; i <= r; i++) {
    for (int j = 4000; j >= 0; j--) {
      dp[i][j] = dp[i - 1][j];
      if (j - v[i].cost >= 0)
        dp[i][j] = max(dp[i][j], dp[i - 1][j - v[i].cost] + v[i].hap);
    }
    for (int j = 1; j <= 4000; j++) {
      dp[i][j] = max(dp[i][j], dp[i][j - 1]);
    }
  }
  for (int i = mid - 1; i >= l; i--) {
    for (int j = 4000; j >= 0; j--) {
      dp[i][j] = dp[i + 1][j];
      if (j - v[i].cost >= 0)
        dp[i][j] = max(dp[i][j], dp[i + 1][j - v[i].cost] + v[i].hap);
    }
    for (int j = 1; j <= 4000; j++) {
      dp[i][j] = max(dp[i][j], dp[i][j - 1]);
    }
  }
  auto it = s.lower_bound(make_pair(make_pair(mid, -1), make_pair(-1, -1)));
  while (it != s.end()) {
    auto val = (*it);
    int l1 = val.first.second;
    int r1 = val.first.first;
    if (l1 <= mid && mid <= r1) {
      if (r1 == mid) {
        ans[val.second.second] = dp[l1][val.second.first];
      } else {
        for (int j = 0; j <= val.second.first; j++) {
          ans[val.second.second] = max(
              ans[val.second.second], dp[l1][j] + dp[r1][val.second.first - j]);
        }
      }
      it++;
      s.erase(val);
    } else {
      break;
    }
  }
  if (mid) solve(l, mid - 1);
  solve(mid + 1, r);
}
int main() {
  cin >> n >> p;
  p--;
  for (int i = 0; i < n; i++) {
    int c, h, t;
    scanf("%d%d%d", &c, &h, &t);
    v.push_back({c, h, t});
  }
  sort(v.begin(), v.end());
  cin >> q;
  for (int i = 0; i < q; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    st aa = {0, 0, a - p};
    int l = lower_bound(v.begin(), v.end(), aa) - v.begin();
    aa.tim = a;
    int r = upper_bound(v.begin(), v.end(), aa) - v.begin();
    s.insert(make_pair(make_pair(r - 1, l), make_pair(b, i)));
  }
  solve(0, v.size() - 1);
  for (int i = 0; i < q; i++) {
    printf("%d\n", ans[i]);
  }
  return 0;
}
