#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000005;
const int limit = 1000000;
struct Info {
  int id;
  int cost;
  Info() {}
  Info(int i, int c) : id(i), cost(c) {}
};
Info info;
int n, m, k;
int arrived[maxn], totol_arrived[2][maxn];
long long totol_arrived_cost[2][maxn];
vector<Info> arrived_store[2][maxn];
void compute(int type, int day) {
  for (int i = 0; i < arrived_store[type][day].size(); ++i) {
    info = arrived_store[type][day][i];
    if (arrived[info.id] == 0) {
      arrived[info.id] = info.cost;
      totol_arrived[type][day] += 1;
      totol_arrived_cost[type][day] += info.cost;
    } else {
      if (arrived[info.id] > info.cost) {
        totol_arrived_cost[type][day] -= arrived[info.id];
        totol_arrived_cost[type][day] += info.cost;
        arrived[info.id] = info.cost;
        ;
      }
    }
  }
}
void init() {
  for (int i = 1; i <= limit; ++i) {
    totol_arrived[0][i] = totol_arrived[0][i - 1];
    totol_arrived_cost[0][i] = totol_arrived_cost[0][i - 1];
    compute(0, i);
  }
  memset(arrived, 0, sizeof(arrived));
  for (int i = limit; i >= 1; --i) {
    totol_arrived[1][i] = totol_arrived[1][i + 1];
    totol_arrived_cost[1][i] = totol_arrived_cost[1][i + 1];
    compute(1, i);
  }
}
long long solve() {
  long long ret = 0x7fffffffffffffffLL;
  for (int u = 1; u <= limit; ++u) {
    int v = u + 1 + k;
    if (u > limit) {
      continue;
    }
    if (totol_arrived[0][u] == n && totol_arrived[1][v] == n) {
      ret = min(ret, totol_arrived_cost[0][u] + totol_arrived_cost[1][v]);
    }
  }
  if (ret == 0x7fffffffffffffffLL) {
    return -1ll;
  } else {
    return ret;
  }
}
int main() {
  int t, u, v, c;
  cin >> n >> m >> k;
  for (int i = 0; i < m; ++i) {
    cin >> t >> u >> v >> c;
    if (u == 0) {
      arrived_store[1][t].push_back(Info(v, c));
    } else {
      arrived_store[0][t].push_back(Info(u, c));
    }
  }
  init();
  long long ans = solve();
  cout << ans << endl;
  return 0;
}
