#include <bits/stdc++.h>   using namespace std;   struct flight {     int d, f, t, c;   };   int main() {     int n, m, k;     scanf( %d %d %d , &n, &m, &k);     vector<flight> flights(m);     for (int i = 0; i < m; i++) {       scanf( %d %d %d %d , &flights[i].d, &flights[i].f, &flights[i].t,             &flights[i].c);     }     sort(flights.begin(), flights.end(),          [](const flight &a, const flight &b) { return a.d < b.d; });     vector<long long> miniCostTo(n + 1, (1LL << 50));     vector<long long> totalTo(1000001, (1LL << 50));     vector<bool> haveTo(n + 1);     int toCounter = 0;     long long costTo = 0;     int toIndex = 0;     for (int i = 0; i <= 1000000; i++) {       if (toCounter == n) {         totalTo[i] = costTo;       }       while (toIndex < m && flights[toIndex].d == i) {         flight f = flights[toIndex];         if (!f.t) {           if (miniCostTo[f.f] > f.c) {             if (miniCostTo[f.f] != (1LL << 50)) costTo -= miniCostTo[f.f] - f.c;             miniCostTo[f.f] = f.c;           }           if (!haveTo[f.f]) {             haveTo[f.f] = true;             costTo += f.c;             toCounter++;           }         }         toIndex++;       }     }     vector<long long> miniCostFrom(n + 1, (1LL << 50));     vector<long long> totalFrom(1000001, (1LL << 50));     vector<bool> haveFrom(n + 1);     int fromCounter = 0;     long long costFrom = 0;     int fromIndex = m - 1;     for (int i = 1000000; i >= 0; i--) {       if (fromCounter == n) {         totalFrom[i] = costFrom;       }       while (fromIndex >= 0 && flights[fromIndex].d == i) {         flight f = flights[fromIndex];         if (!f.f) {           if (miniCostFrom[f.t] > f.c) {             if (miniCostFrom[f.t] != (1LL << 50))               costFrom -= miniCostFrom[f.t] - f.c;             miniCostFrom[f.t] = f.c;           }           if (!haveFrom[f.t]) {             haveFrom[f.t] = true;             costFrom += f.c;             fromCounter++;           }         }         fromIndex--;       }     }     long long cheapest = (1LL << 50);     for (int i = 0; i + k - 1 <= 1000000; i++) {       cheapest = min(cheapest, totalTo[i] + totalFrom[i + k - 1]);     }     if (cheapest == (1LL << 50))       printf( -1 n );     else       printf( %I64d n , cheapest);     return 0;   }   