#include <bits/stdc++.h>
using namespace std;
long long dp1[1000005], dp2[1000005], cost[1000005];
struct node {
  int r, m, c;
  bool operator<(const node &st) const { return r < st.r; }
};
vector<node> from, to;
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  while (m--) {
    int t, f, d, cc;
    scanf("%d%d%d%d", &t, &f, &d, &cc);
    if (d == 0)
      to.push_back({t, f, cc});
    else
      from.push_back({t, d, cc});
  }
  sort(from.begin(), from.end());
  sort(to.begin(), to.end());
  int cnt = 0, s = 0;
  long long sum = 0;
  for (int i = 1; i <= 1e6; i++) {
    while (cnt < to.size() && to[cnt].r == i) {
      if (cost[to[cnt].m] == 0) {
        cost[to[cnt].m] = to[cnt].c;
        s++;
        sum += to[cnt].c;
      } else if (to[cnt].c < cost[to[cnt].m]) {
        sum += (to[cnt].c - cost[to[cnt].m]);
        cost[to[cnt].m] = to[cnt].c;
      }
      cnt++;
    }
    if (s == n) dp1[i] = sum;
  }
  memset(cost, 0, sizeof(cost));
  sum = 0;
  cnt = from.size() - 1, s = 0;
  for (int i = 1e6; i >= 1; i--) {
    while (cnt >= 0 && from[cnt].r == i) {
      if (cost[from[cnt].m] == 0) {
        cost[from[cnt].m] = from[cnt].c;
        s++;
        sum += from[cnt].c;
      } else if (from[cnt].c < cost[from[cnt].m]) {
        sum += (from[cnt].c - cost[from[cnt].m]);
        cost[from[cnt].m] = from[cnt].c;
      }
      cnt--;
    }
    if (s == n) dp2[i] = sum;
  }
  long long ans = -1;
  for (int i = 1; i <= 1e6; i++) {
    if (dp1[i] && i + k + 1 <= 1e6 && dp2[i + k + 1]) {
      if (ans == -1)
        ans = dp1[i] + dp2[i + k + 1];
      else
        ans = min(ans, dp1[i] + dp2[i + k + 1]);
    }
  }
  printf("%lld\n", ans);
  return 0;
}
