#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
template <class T>
inline bool MX(T &l, const T &r) {
  return l < r ? l = r, 1 : 0;
}
template <class T>
inline bool MN(T &l, const T &r) {
  return l > r ? l = r, 1 : 0;
}
int N;
int Q;
int L[1145];
int R[1145];
int cnt[1145];
bool check() {
  multiset<int> rs;
  vector<pair<int, int> > evs;
  for (int(i) = 0; (i) < (N); ++(i)) {
    evs.emplace_back(pair<int, int>(L[i], R[i]));
  }
  sort((evs).begin(), (evs).end(), greater<pair<int, int> >());
  for (int(i) = 0; (i) < (N); ++(i)) {
    if (!rs.empty() && *rs.begin() <= i) return false;
    while (!evs.empty() && evs.back().first == i) {
      rs.insert(evs.back().second);
      evs.pop_back();
    }
    for (int(j) = 0; (j) < (cnt[i]); ++(j)) {
      if (rs.empty()) return false;
      rs.erase(rs.begin());
    }
  }
  assert(rs.empty());
  return true;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cout << fixed << setprecision(0);
  cin >> N >> Q;
  for (int(i) = 0; (i) < (N); ++(i)) R[i] = N;
  for (int(i) = 0; (i) < (Q); ++(i)) {
    int t, l, r, v;
    cin >> t >> l >> r >> v;
    --l;
    --v;
    if (t == 1) {
      for (int(j) = l; (j) < (r); ++(j)) {
        MX(L[j], v);
      }
    } else if (t == 2) {
      ++v;
      for (int(j) = l; (j) < (r); ++(j)) {
        MN(R[j], v);
      }
    } else
      assert(0);
  }
  for (int(i) = 0; (i) < (N); ++(i)) {
    if (R[i] - L[i] <= 0) {
      cout << "-1\n";
      return 0;
    }
    cnt[L[i]]++;
  }
  assert(check());
  while (1) {
    bool found = 0;
    for (int(i) = 0; (i) < (N); ++(i)) {
      for (int(j) = 0; (j) < (N); ++(j)) {
        if (i == j) continue;
        if (cnt[i] > cnt[j] + 1) {
          cnt[i]--;
          cnt[j]++;
          if (!check()) {
            cnt[i]++;
            cnt[j]--;
          } else {
            found = 1;
            goto L_FOUND;
          }
        }
      }
    }
  L_FOUND:
    if (!found) break;
  }
  int ans = 0;
  for (int(i) = 0; (i) < (N); ++(i)) ans += cnt[i] * cnt[i];
  cout << ans << endl;
}
