#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e6 + 9;
struct mb {
  int d, f, t, c;
};
long long dp1[MAXN], dp2[MAXN];
int v[MAXN];
vector<mb> arr, dep;
bool cmp1(mb a, mb b) {
  if (a.d < b.d) return true;
  return false;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    mb x;
    cin >> x.d >> x.f >> x.t >> x.c;
    if (x.t == 0)
      arr.push_back(x);
    else
      dep.push_back(x);
  }
  sort(arr.begin(), arr.end(), cmp1);
  long long cost = 0;
  int rem = n, id = 0;
  for (mb x : arr) {
    if (v[x.f] == 0) {
      cost += x.c;
      v[x.f] = x.c;
      rem--;
    }
    if (v[x.f] > x.c) {
      cost -= v[x.f] - x.c;
      v[x.f] = x.c;
    }
    id++;
    if (rem == 0) break;
  }
  if (rem != 0) return cout << "-1\n", 0;
  dp1[arr[id - 1].d] = cost;
  for (; id < arr.size(); id++)
    if (v[arr[id].f] > arr[id].c) {
      dp1[arr[id].d] = dp1[arr[id - 1].d] - (v[arr[id].f] - arr[id].c);
      v[arr[id].f] = arr[id].c;
    } else
      dp1[arr[id].d] = dp1[arr[id - 1].d];
  long long cur = 0;
  for (int i = 0; i < MAXN; i++) {
    if (dp1[i] != 0) cur = dp1[i];
    dp1[i] = cur;
  }
  fill(v, v + MAXN, 0);
  sort(dep.rbegin(), dep.rend(), cmp1);
  cost = 0;
  rem = n, id = 0;
  for (mb x : dep) {
    if (v[x.t] == 0) {
      cost += x.c;
      v[x.t] = x.c;
      rem--;
    }
    if (v[x.t] > x.c) {
      cost -= v[x.t] - x.c;
      v[x.t] = x.c;
    }
    id++;
    if (rem == 0) break;
  }
  if (rem != 0) return cout << "-1\n", 0;
  dp2[dep[id - 1].d] = cost;
  for (; id < dep.size(); id++)
    if (v[dep[id].t] > dep[id].c) {
      dp2[dep[id].d] = dp2[dep[id - 1].d] - (v[dep[id].t] - dep[id].c);
      v[dep[id].t] = dep[id].c;
    } else
      dp2[dep[id].d] = dp2[dep[id - 1].d];
  cur = 0;
  for (int i = MAXN - 1; i >= 0; i--) {
    if (dp2[i] != 0) cur = dp2[i];
    dp2[i] = cur;
  }
  long long res = 1e18;
  for (int i = 1; i + k + 1 < MAXN; i++)
    if (dp1[i] && dp2[i + k + 1] && res > dp1[i] + dp2[i + k + 1])
      res = dp1[i] + dp2[i + k + 1];
  if (res == 1e18) res = -1;
  cout << res << "\n";
}
