#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
struct node1 {
  int f, ti;
  long long c;
} a[N];
struct node2 {
  int to, ti;
  long long c;
} b[N];
bool cmp1(node1 a, node1 b) { return a.ti < b.ti; };
bool cmp2(node2 a, node2 b) { return a.ti > b.ti; };
bool vis[N];
long long pre[N];
long long dp1[N], dp2[N];
int main() {
  int n, m, k, d, f, t;
  long long c;
  scanf("%d%d%d", &n, &m, &k);
  int cnt1 = 0, cnt2 = 0;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%I64d", &d, &f, &t, &c);
    if (f == 0) {
      cnt2++;
      b[cnt2].to = t, b[cnt2].c = c, b[cnt2].ti = d;
    } else {
      cnt1++;
      a[cnt1].f = f, a[cnt1].c = c, a[cnt1].ti = d;
    }
  }
  int num = 0;
  long long sum = 0;
  sort(a + 1, a + cnt1 + 1, cmp1);
  for (int i = 1; i <= cnt1; i++) {
    if (!vis[a[i].f]) {
      vis[a[i].f] = 1;
      num++;
      pre[a[i].f] = a[i].c;
      sum += a[i].c;
    } else {
      if (pre[a[i].f] > a[i].c) {
        sum += (a[i].c - pre[a[i].f]);
        pre[a[i].f] = a[i].c;
      }
    }
    if (num == n) dp1[a[i].ti] = sum;
  }
  sort(b + 1, b + cnt2 + 1, cmp2);
  memset(vis, 0, sizeof(vis));
  num = 0;
  sum = 0;
  for (int i = 1; i <= cnt2; i++) {
    if (!vis[b[i].to]) {
      vis[b[i].to] = 1;
      num++;
      pre[b[i].to] = b[i].c;
      sum += b[i].c;
    } else {
      if (pre[b[i].to] > b[i].c) {
        sum += (b[i].c - pre[b[i].to]);
        pre[b[i].to] = b[i].c;
      }
    }
    if (num == n) dp2[b[i].ti] = sum;
  }
  for (int i = 1; i + 1 < N; i++)
    if (!dp1[i + 1]) dp1[i + 1] = dp1[i];
  for (int i = N - 1; i > 0; i--)
    if (!dp2[i - 1]) dp2[i - 1] = dp2[i];
  long long ans = 1e18;
  for (int i = 1; i + k + 1 < N; i++) {
    if (dp1[i] == 0 || dp2[i + k + 1] == 0) continue;
    ans = min(ans, dp1[i] + dp2[i + k + 1]);
  }
  if (ans >= 1e18)
    printf("-1\n");
  else
    printf("%I64d\n", ans);
  return 0;
}
