#include <bits/stdc++.h>
using namespace std;
const int N = 100000;
const int D = 1000000;
vector<pair<int, int>> source[D + 1], target[D + 1];
long long cost_to[D + 1], cost_from[D + 1];
int min_cost[N + 1];
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (t == 0) {
      source[d].emplace_back(f, c);
    } else if (f == 0) {
      target[d].emplace_back(t, c);
    }
  }
  long long cost = 0;
  int members = 0;
  for (int i = 1; i <= n; i++) {
    min_cost[i] = -1;
  }
  for (int d = 1; d <= D; d++) {
    for (pair<int, int> t : source[d]) {
      if (min_cost[t.first] == -1) {
        min_cost[t.first] = t.second;
        cost += t.second;
        members++;
      } else if (t.second < min_cost[t.first]) {
        cost -= min_cost[t.first];
        cost += t.second;
        min_cost[t.first] = t.second;
      }
    }
    if (members == n) {
      cost_to[d] = cost;
    } else {
      cost_to[d] = -1;
    }
  }
  cost = 0;
  members = 0;
  for (int i = 1; i <= n; i++) {
    min_cost[i] = -1;
  }
  for (int d = D; d >= 1; d--) {
    for (pair<int, int> t : target[d]) {
      if (min_cost[t.first] == -1) {
        min_cost[t.first] = t.second;
        cost += t.second;
        members++;
      } else if (t.second < min_cost[t.first]) {
        cost -= min_cost[t.first];
        cost += t.second;
        min_cost[t.first] = t.second;
      }
    }
    if (members == n) {
      cost_from[d] = cost;
    } else {
      cost_from[d] = -1;
    }
  }
  long long ans = -1;
  for (int d = 1; d + k + 1 <= D; d++) {
    if (cost_to[d] != -1 && cost_from[d + k + 1] != -1) {
      long long cost = cost_to[d] + cost_from[d + k + 1];
      if (ans == -1 || cost < ans) {
        ans = cost;
      }
    }
  }
  printf("%lld\n", ans);
  return 0;
}
