#include <bits/stdc++.h>
using namespace std;
const long long LLINF = 8e18;
const int MOD = 1e9 + 7;
const int INF = 2e9;
const int N = 1e5;
struct data {
  int day, from, to, cost;
} a[N];
int n, m, k, cnt, j, was, will;
int mn[N];
long long tmp, ans = LLINF;
set<pair<int, int>> s[N];
bool cmp(data a, data b) { return (a.day < b.day); }
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    cin >> a[i].day >> a[i].from >> a[i].to >> a[i].cost;
    if (a[i].from == 0) s[a[i].to - 1].insert(make_pair(a[i].cost, a[i].day));
  }
  for (int i = 0; i < n; i++) {
    if (s[i].size() == 0) {
      cout << -1;
      return 0;
    }
    tmp += (*s[i].begin()).first;
  }
  sort(a, a + m, cmp);
  for (int i = 0; i < m; i++) {
    if (a[i].to == 0) {
      was = mn[a[i].from - 1];
      if (was == 0) {
        cnt++;
        mn[a[i].from - 1] = a[i].cost;
        tmp += a[i].cost;
      } else {
        will = mn[a[i].from - 1] = min(mn[a[i].from - 1], a[i].cost);
        tmp -= was - will;
      }
    }
    while (a[j].day - a[i].day < k + 1) {
      if (a[j].from == 0) {
        was = (*s[a[j].to - 1].begin()).first;
        s[a[j].to - 1].erase(make_pair(a[j].cost, a[j].day));
        if (s[a[j].to - 1].size() == 0) {
          if (ans == LLINF)
            cout << -1;
          else
            cout << ans;
          return 0;
        } else {
          will = (*s[a[j].to - 1].begin()).first;
          tmp -= was - will;
        }
      }
      j++;
    }
    if (cnt == n) ans = min(ans, tmp);
  }
  return 0;
}
