#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 500000;
const int LOG_MAX_N = 18;
const int INF = 1000000009;
int nTest;
int n;
int m;
int k;
int b0;
int a[MAX_N + 9];
int b[MAX_N + 9];
int c[MAX_N + 9];
vector<int> vA;
vector<int> vId[MAX_N + 9];
int it[(1 << LOG_MAX_N + 2) + 9];
int lz[(1 << LOG_MAX_N + 2) + 9];
long long ans;
int cnt;
void Down(int x) {
  it[x * 2] += lz[x];
  lz[x * 2] += lz[x];
  it[x * 2 + 1] += lz[x];
  lz[x * 2 + 1] += lz[x];
  lz[x] = 0;
}
void Build(int x, int low, int high) {
  lz[x] = 0;
  if (low == high) {
    it[x] = b0 - vA[low - 1];
    return;
  }
  int mid = (low + high) / 2;
  Build(x * 2, low, mid);
  Build(x * 2 + 1, mid + 1, high);
  it[x] = max(it[x * 2], it[x * 2 + 1]);
}
void Update(int x, int low, int high, int l, int h, int val) {
  if (low > h || high < l) {
    return;
  }
  if (low >= l && high <= h) {
    it[x] += val;
    lz[x] += val;
    return;
  }
  Down(x);
  int mid = (low + high) / 2;
  Update(x * 2, low, mid, l, h, val);
  Update(x * 2 + 1, mid + 1, high, l, h, val);
  it[x] = max(it[x * 2], it[x * 2 + 1]);
}
int Query(int x, int low, int high, int l, int h) {
  if (low > h || high < l) {
    return -INF;
  }
  if (low >= l && high <= h) {
    return it[x];
  }
  Down(x);
  int mid = (low + high) / 2;
  return max(Query(x * 2, low, mid, l, h),
             Query(x * 2 + 1, mid + 1, high, l, h));
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> nTest;
  for (int iTest = 1; iTest <= nTest; iTest++) {
    cin >> n >> m >> k >> b0;
    vA = vector<int>({0, m});
    for (int i = 1; i <= n; i++) {
      cin >> a[i] >> b[i] >> c[i];
      vA.push_back(a[i]);
    }
    sort(vA.begin(), vA.end());
    vA.erase(unique(vA.begin(), vA.end()), vA.end());
    fill(vId, vId + vA.size() + 1, vector<int>());
    for (int i = 1; i <= n; i++) {
      a[i] = lower_bound(vA.begin(), vA.end(), a[i]) - vA.begin() + 1;
      vId[a[i]].push_back(i);
    }
    Build(1, 1, vA.size() - 1);
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        pq;
    ans = 0;
    cnt = 0;
    for (int i = 1; i <= vA.size() - 1; i++) {
      for (int id : vId[i]) {
        pq.push(make_pair(c[id], id));
      }
      int x = cnt + b0 - (vA[i] - 1);
      while (x < 1 && !pq.empty()) {
        int id = pq.top().second;
        int tmp = min({1 - x, b[id],
                       k - Query(1, 1, vA.size() - 1, a[id], vA.size() - 1)});
        ans += (long long)tmp * c[id];
        cnt += tmp;
        x += tmp;
        b[id] -= tmp;
        Update(1, 1, vA.size() - 1, a[id], vA.size() - 1, tmp);
        if (x < 1) {
          pq.pop();
        }
      }
      if (x < 1) {
        ans = -1;
        break;
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
