#include <bits/stdc++.h>
using namespace std;
#define int long long
#define inf (long long)(1e15)
signed main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
//start here
int N,k;cin >> N >> k;
vector<vector<pair<int,int>>> loc(5);
for(int i = 1;i <= N;i++){
int t,x,y,c;
cin >> t >> x >> y >> c;
c++;
if(t <= 2) loc[t].push_back({x,c});
else loc[t].push_back({y,c});
}
auto solve = [&](vector<pair<int,int>> right,vector<pair<int,int>> left){
// vector<pair<int,int>> arr;
// for(auto [loc,cost]:left){
// arr.push_back({nloc,-cost});
// }
// for(auto [loc,cost]:right){
// arr.push_back({nloc,cost});
// }
// sort(arr.begin(),arr.end(),[](auto a,auto b){
// if(a.second > 0 && b.second > 0){
// return a.first < b.first;
// }else if(a.second < 0 && b.second < 0){
// return a.first < b.first;
// }else if(a.second > 0 && b.second < 0){
// return b.first+1 < a.first;
// }else{
// return a.first+1 < b.first;
// }
// });
sort(left.begin(),left.end());
sort(right.begin(),right.end());
vector<pair<int,int>> arr;
for(auto [loc,cost]:left){
int nloc = lower_bound(right.begin(),right.end(),pair<int,int>{loc+2,-1LL})-right.begin();
arr.push_back({nloc,-cost});
}
for(int i = 0;i < right.size();i++){
auto [loc,cost] = right[i];
arr.push_back({i,cost});
}
sort(arr.begin(),arr.end());
int prev = inf,ans = inf;
for(auto [loc,cost]:arr){
// cout << "??" << loc << " " << cost << endl;
if(cost > 0) prev = min(prev,abs(cost));
else ans = min(ans,prev+abs(cost));
}
return ans;
};
int ans = min(solve(loc[2],loc[1]),solve(loc[4],loc[3]));
// for(auto &i:ans1) cout << i << " ";cout << endl;
// for(auto &i:ans2) cout << i << " ";cout << endl;
if(ans < inf){
cout << ans;
}else{
cout << "-1\n";
}
// cout << max(solve(loc[2],loc[1]),solve(loc[4],loc[3]));
}