#include <bits/stdc++.h>
using namespace std;
const long long md = 1e9 + 7;
long long n, prefix[1000005], suffix[1000005];
struct flight {
  int d, f, t, c;
} a[100005];
int vis[100005];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long q, m, k, h, ans = 0, sum = 0, p, x, y;
  cin >> n >> m >> k;
  for (int i = 0; i < m; ++i) {
    cin >> a[i].d >> a[i].f >> a[i].t >> a[i].c;
  }
  sort(a, a + m, [](flight& i, flight& j) { return i.d < j.d; });
  fill_n(vis, 100005, -1);
  fill_n(prefix, 1000005, 1e16);
  fill_n(suffix, 1000005, 1e16);
  int ptr = 0, cnt = 0;
  for (int i = 1; i < 1000005 && ptr < m; ++i) {
    for (; a[ptr].d == i && ptr < m; ++ptr) {
      if (a[ptr].f == 0) continue;
      if (vis[a[ptr].f] == -1) {
        ++cnt;
        vis[a[ptr].f] = a[ptr].c;
        ans += a[ptr].c;
      } else if (vis[a[ptr].f] > a[ptr].c) {
        ans += a[ptr].c - vis[a[ptr].f];
        vis[a[ptr].f] = a[ptr].c;
      }
    }
    if (cnt >= n) prefix[i] = ans;
  }
  fill_n(vis, 100005, -1);
  ptr = m - 1, cnt = 0, ans = 0;
  for (int i = 1000005; --i && ptr >= 0;) {
    for (; a[ptr].d == i && ptr >= 0; --ptr) {
      if (a[ptr].t == 0) continue;
      if (vis[a[ptr].t] == -1) {
        ++cnt;
        vis[a[ptr].t] = a[ptr].c;
        ans += a[ptr].c;
      } else if (vis[a[ptr].t] > a[ptr].c) {
        ans += a[ptr].c - vis[a[ptr].t];
        vis[a[ptr].t] = a[ptr].c;
      }
    }
    if (cnt >= n) suffix[i] = ans;
  }
  ans = 1e17;
  for (int i = 1; i + k < 1000004; ++i) {
    ans = min(prefix[i] + suffix[i + k + 1], ans);
  }
  cout << (ans < 1e16 ? ans : -1);
}
