#include <bits/stdc++.h>
const int MAXINT = 2147483640;
const long long MAXLL = 9223372036854775800LL;
const long long MAXN = 1123456;
using namespace std;
pair<pair<long long, long long>, pair<long long, long long> > a[MAXN];
vector<long long> v[2][MAXN];
set<pair<long long, long long> > S[MAXN];
long long kol[2], c[2][MAXN], num[2][MAXN], s[MAXN];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  srand(time(0));
  long long n, m, k, i, j, z, d, r0, r1, l1, ans = MAXLL, sum = 0;
  cin >> n >> m >> k;
  for (i = 1; i <= m; i++) {
    cin >> a[i].first.first >> a[i].second.first >> a[i].second.second >>
        a[i].first.second;
    if (!a[i].second.first) a[i].second.first = 1;
    if (!a[i].second.second)
      a[i].second.second = a[i].second.first, a[i].second.first = 0;
  }
  sort(a + 1, a + m + 1);
  kol[0] = n;
  kol[1] = n;
  r0 = r1 = 1;
  l1 = 1;
  while (r1 <= m) {
    if (a[r1].second.first == 1) {
      if (c[1][a[r1].second.second] == 0) --kol[1];
      sum -= c[1][a[r1].second.second];
      S[a[r1].second.second].insert(make_pair(a[r1].first.second, r1));
      c[1][a[r1].second.second] = S[a[r1].second.second].begin()->first;
      sum += c[1][a[r1].second.second];
    }
    ++r1;
  }
  for (d = 1; d <= 10000000; d++) {
    while (a[r0].first.first == d && r0 <= m) {
      if (a[r0].second.first == 0) {
        if (c[0][a[r0].second.second] == 0) --kol[0];
        sum -= c[0][a[r0].second.second];
        s[a[r0].second.second] =
            min(s[a[r0].second.second], a[r0].first.second);
        if (s[a[r0].second.second] == 0)
          s[a[r0].second.second] = a[r0].first.second;
        c[0][a[r0].second.second] = s[a[r0].second.second];
        sum += c[0][a[r0].second.second];
      }
      ++r0;
    }
    while (a[l1].first.first <= d + k && l1 <= m) {
      if (a[l1].second.first == 1) {
        S[a[l1].second.second].erase(make_pair(a[l1].first.second, l1));
        sum -= c[1][a[l1].second.second];
        if (S[a[l1].second.second].size() == 0)
          ++kol[1];
        else {
          c[1][a[l1].second.second] = S[a[l1].second.second].begin()->first;
          sum += c[1][a[l1].second.second];
        }
      }
      ++l1;
    }
    if (kol[0] + kol[1] == 0) ans = min(ans, sum);
    if (r1 > m && r0 > m) break;
  }
  if (ans == MAXLL) ans = -1;
  cout << ans << "\n";
  return 0;
}
