#include <bits/stdc++.h>
using namespace std;
const int N = 1000100;
vector<pair<int, int> > e0[N], e1[N];
int v0[N], v1[N], ml, mr;
long long s0[N], s1[N];
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (register int i = 1; i <= m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (!t)
      e0[d].push_back(make_pair(f, c));
    else
      e1[d].push_back(make_pair(t, c));
  }
  int cnt = 0;
  for (register int i = 1; i <= 1e6; i++) {
    s0[i] = s0[i - 1];
    if (e0[i].size())
      for (register int j = 0; j <= e0[i].size() - 1; j++) {
        int tmp = e0[i][j].first;
        if (!v0[tmp]) {
          v0[tmp] = e0[i][j].second, s0[i] += e0[i][j].second;
          if (++cnt == n) ml = i;
        } else if (v0[tmp] > e0[i][j].second)
          s0[i] += e0[i][j].second - v0[tmp], v0[tmp] = e0[i][j].second;
      }
  }
  cnt = 0;
  for (int i = 1e6; i; i--) {
    s1[i] = s1[i + 1];
    if (e1[i].size())
      for (register int j = 0; j <= e1[i].size() - 1; j++) {
        int tmp = e1[i][j].first;
        if (!v1[tmp]) {
          v1[tmp] = e1[i][j].second, s1[i] += e1[i][j].second;
          if (++cnt == n) mr = i;
        } else if (v1[tmp] > e1[i][j].second)
          s1[i] += e1[i][j].second - v1[tmp], v1[tmp] = e1[i][j].second;
      }
  }
  if (!ml || !mr)
    printf("-1\n");
  else {
    long long ans = 1e18;
    for (int i = ml + 1; i + k - 1 < mr; i++)
      ans = min(ans, s0[i - 1] + s1[i + k]);
    if (ans == 1e18)
      printf("-1\n");
    else
      printf("%lld\n", ans);
  }
  return 0;
}
