#include <bits/stdc++.h>
using namespace std;
int n, m, k;
pair<pair<int, int>, pair<int, int> > a[100005];
int sl[100005], sr[100005], pl = 1000000, pr;
long long l[1000005], r[1000005];
int ll, rr;
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &a[i].first.first, &a[i].first.second, &a[i].second.first,
          &a[i].second.second);
  }
  sort(&a[1], &a[m + 1]);
  for (int i = 1; i <= n; i++) sl[i] = 1000001, l[0] += sl[i];
  ll = n;
  int j = 1;
  for (int i = 1; i <= 1000000; i++) {
    l[i] = l[i - 1];
    while (a[j].first.first == i && j <= m) {
      if (a[j].first.second) {
        int t = a[j].first.second;
        if (sl[t] == 1000001)
          ll--, l[i] -= sl[t] - a[j].second.second, sl[t] = a[j].second.second;
        else if (sl[t] > a[j].second.second)
          l[i] -= sl[t] - a[j].second.second, sl[t] = a[j].second.second;
      }
      j++;
    }
    if (ll == 0) pl = min(pl, i);
  }
  for (int i = 1; i <= n; i++) sr[i] = 1000001, r[1000001] += sr[i];
  rr = n;
  j = m;
  for (int i = 1000000; i >= 1; i--) {
    r[i] = r[i + 1];
    while (a[j].first.first == i && j) {
      if (a[j].second.first) {
        int t = a[j].second.first;
        if (sr[t] == 1000001)
          rr--, r[i] -= sr[t] - a[j].second.second, sr[t] = a[j].second.second;
        else if (sr[t] > a[j].second.second)
          r[i] -= sr[t] - a[j].second.second, sr[t] = a[j].second.second;
      }
      j--;
    }
    if (rr == 0) pr = max(i, pr);
  }
  long long ans = (1ll << 60);
  for (int i = pl; i + k + 1 <= pr; i++) ans = min(ans, l[i] + r[i + k + 1]);
  cout << (ans == (1ll << 60) ? -1 : ans) << endl;
  return 0;
}
