#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
long long powmod(long long a, long long b) {
  long long res = 1;
  a %= mod;
  for (; b; b >>= 1) {
    if (b & 1) res = res * a % mod;
    a = a * a % mod;
  }
  return res;
}
const int N = 20100, M = 4010;
int dp[10100][M], pd[M];
int n, p, grop, q, c[N], h[N], t[N], a[N], b[N], ret[N];
vector<int> evt[N], qc[N];
vector<pair<int, int> > rc[N], pc[N], qr[N];
void gao(vector<pair<int, int> > &a) {
  for (int i = 0; i < p + 1; i++) evt[i].clear();
  for (int i = 0; i < ((int)(a).size()); i++)
    evt[p + 1 - a[i].first].push_back(a[i].second);
  for (int i = 0; i < 4001; i++) dp[0][i] = 0;
  for (int i = 1; i < p + 1; i++) {
    for (int j = 0; j < 4001; j++) dp[i][j] = dp[i - 1][j];
    for (int j = 0; j < ((int)(evt[i]).size()); j++) {
      int cs = c[evt[i][j]], ch = h[evt[i][j]];
      for (int k = 4001 - 1; k >= cs; k--)
        dp[i][k] = max(dp[i][k - cs] + ch, dp[i][k]);
    }
  }
}
void gaoo(vector<pair<int, int> > &a) {
  for (int i = 0; i < p + 1; i++) evt[i].clear();
  for (int i = 0; i < ((int)(a).size()); i++)
    evt[p + 1 - a[i].first].push_back(a[i].second);
  for (int i = 0; i < 4001; i++) pd[i] = 0;
  for (int i = 1; i < p + 1; i++) {
    for (int j = 0; j < ((int)(evt[i]).size()); j++) {
      int cs = c[evt[i][j]], ch = h[evt[i][j]];
      for (int k = 4001 - 1; k >= cs; k--) pd[k] = max(pd[k - cs] + ch, pd[k]);
    }
    for (int j = 0; j < ((int)(qr[i]).size()); j++) {
      int id = qr[i][j].second, ct = qr[i][j].first;
      for (int k = 0; k < b[id] + 1; k++)
        ret[id] = max(ret[id], dp[ct][k] + pd[b[id] - k]);
    }
  }
}
int main() {
  scanf("%d%d", &n, &p);
  grop = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d%d%d", c + i, h + i, t + i);
    if (t[i] % p == 0)
      pc[t[i] / p - 1].push_back(make_pair(p, i));
    else
      pc[t[i] / p].push_back(make_pair(t[i] % p, i)),
          rc[t[i] / p].push_back(make_pair(p - t[i] % p, i));
    grop = max(grop, t[i] / p + 2);
  }
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    scanf("%d%d", a + i, b + i);
    qc[a[i] / p].push_back(i);
  }
  for (int i = 0; i < grop; i++) {
    if (i) gao(pc[i - 1]);
    for (int j = 0; j < p + 1; j++) qr[j].clear();
    for (int j = 0; j < ((int)(qc[i]).size()); j++) {
      int id = qc[i][j], ct = p - a[id] % p, rt = a[id] % p + 1;
      qr[rt].push_back(make_pair(ct, id));
    }
    gaoo(rc[i]);
  }
  for (int i = 0; i < q; i++) printf("%d\n", ret[i]);
}
