#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#define endl '\n'
#pragma GCC optimize("Ofast")
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair < int, int >;
using pll = pair < ll, ll >;
const ll INF = 2e18;
const ll DIM = 400007;
const ll DIMQ = 2007;
const ld PI = 3.1415926535;
const int mod = 998244353;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef IloveCP
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector < vector < pll > > a(4);
vector < ll > c(n);
for(int i = 0; i < n; i++) {
ll t, x, y;
cin >> t >> x >> y >> c[i];
t--;
if(t < 2) a[t].push_back({x, i});
else a[t].push_back({y, i});
}
for(int t = 0; t < 4; t++) {
sort(a[t].begin(), a[t].end());
}
ll res = INF;
int ptr = 0;
ll mi = INF;
for(int i = 0; i < a[0].size(); i++) {
while(ptr < a[1].size() && a[1][ptr].first <= a[0][i].first) {
mi = min(mi, c[a[1][ptr].second]);
ptr++;
}
res = min(res, mi + c[a[0][i].second]);
}
ptr = 0;
mi = INF;
for(int i = 0; i < a[2].size(); i++) {
while(ptr < a[3].size() && a[3][ptr].first <= a[2][i].first) {
mi = min(mi, c[a[3][ptr].second]);
ptr++;
}
res = min(res, mi + c[a[2][i].second]);
}
cout << (res == INF ? -1 : res) << endl;
return 0;
}