#include <bits/stdc++.h>
using namespace std;
const int maxN = (int)1e5 + 100;
const int INF = 1e9;
const int maxD = 1e6 + 100;
const int modulo = maxN;
int d[maxN], f[maxN], t[maxN], c[maxN];
int start[maxN], finish[maxN];
long long cost0[maxD], costN[maxD];
vector<pair<int, int> > FROM[maxD], TO[maxD];
long long rsq[maxN * 4];
void replace(int i, long long x) {
  i += modulo - 1;
  rsq[i] = min(rsq[i], x);
  i /= 2;
  while (i > 0) {
    rsq[i] = rsq[i + i] + rsq[i + i + 1];
    i /= 2;
  }
}
long long getsum(int l, int r) {
  int i = l + modulo - 1, j = r + modulo - 1;
  long long ans = 0;
  while (i <= j) {
    if (i % 2 == 1) ans += rsq[i];
    if (j % 2 == 0) ans += rsq[j];
    i = (i + 1) / 2;
    j = (j - 1) / 2;
  }
  return ans;
}
void solveTask() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; ++i) {
    scanf("%d%d%d%d", &d[i], &f[i], &t[i], &c[i]);
  }
  for (int i = 1; i <= n; ++i) {
    start[i] = INF;
    finish[i] = -INF;
  }
  for (int i = 1; i <= m; ++i) {
    if (t[i] == 0) start[f[i]] = min(start[f[i]], d[i] + 1);
    if (f[i] == 0) finish[t[i]] = max(finish[t[i]], d[i] - 1);
    if (t[i] == 0) {
      FROM[d[i]].push_back(make_pair(f[i], c[i]));
    }
    if (f[i] == 0) {
      TO[d[i]].push_back(make_pair(t[i], c[i]));
    }
  }
  for (int i = 1; i <= n; ++i) {
    if (start[i] == INF || finish[i] == -INF) {
      cout << -1 << endl;
      return;
    }
  }
  int minK = -INF, maxK = INF;
  for (int i = 1; i <= n; ++i) {
    minK = max(minK, start[i]);
    maxK = min(maxK, finish[i]);
  }
  if (maxK - minK + 1 < k) {
    cout << -1 << endl;
    return;
  }
  for (int i = 0; i <= 1e6; ++i) {
    cost0[i] = 1e18, costN[i] = 1e18;
  }
  int possibleL = minK, possibleR = maxK - k + 1;
  for (int i = 0; i < maxN * 4; ++i) {
    rsq[i] = 1e13;
  }
  for (int t = 1; t < possibleL; ++t) {
    for (int i = 0; i < FROM[t].size(); ++i) {
      pair<int, int> cur_pair = FROM[t][i];
      replace(cur_pair.first, cur_pair.second);
    }
  }
  for (int i = possibleL; i <= possibleR; ++i) {
    cost0[i] = getsum(1, n);
    for (int j = 0; j < FROM[i].size(); ++j) {
      pair<int, int> cur_pair = FROM[i][j];
      replace(cur_pair.first, cur_pair.second);
    }
  }
  for (int i = 0; i < maxN * 4; ++i) {
    rsq[i] = 1e13;
  }
  for (int t = 1e6; t >= possibleR + k; --t) {
    for (int i = 0; i < TO[t].size(); ++i) {
      pair<int, int> cur_pair = TO[t][i];
      replace(cur_pair.first, cur_pair.second);
    }
  }
  for (int t = possibleR + k - 1; t >= k; --t) {
    costN[t - k + 1] = getsum(1, n);
    for (int j = 0; j < TO[t].size(); ++j) {
      pair<int, int> cur_pair = TO[t][j];
      replace(cur_pair.first, cur_pair.second);
    }
  }
  long long answer = 1e18;
  for (int i = 0; i <= 1e6; ++i) {
    answer = min(answer, cost0[i] + costN[i]);
  }
  if (answer < 1e18) {
    cout << answer << endl;
  } else {
    cout << -1 << endl;
  }
}
int main() {
  solveTask();
  return 0;
}
