#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n, q;
  cin >> n >> q;
  vector<pair<long long, long long>> a(n, {1, n});
  for (long long i = 0; i < q; ++i) {
    long long t, l, r, v;
    cin >> t >> l >> r >> v;
    --l;
    --r;
    if (t == 1) {
      for (long long j = l; j <= r; ++j) {
        a[j].first = max(a[j].first, v);
      }
    } else {
      for (long long j = l; j <= r; ++j) {
        a[j].second = min(a[j].second, v);
      }
    }
  }
  for (long long i = 0; i < n; ++i) {
    if (a[i].first > a[i].second) {
      cout << -1;
      return;
    }
  }
  vector<pair<pair<long long, long long>, long long>> e;
  vector<vector<long long>> graf(2 * n + 2, vector<long long>());
  for (long long i = 1; i <= n; ++i) {
    for (long long j = 0, temp = 1; j < n; ++j, temp += 2) {
      graf[0].push_back(e.size());
      e.push_back({{i, 1}, temp});
      graf[i].push_back(e.size());
      e.push_back({{0, 0}, -temp});
    }
  }
  for (long long i = 0; i < n; ++i) {
    for (long long j = a[i].first; j <= a[i].second; ++j) {
      graf[j].push_back(e.size());
      e.push_back({{n + i + 1, 1}, 0});
      graf[n + i + 1].push_back(e.size());
      e.push_back({{j, 0}, 0});
    }
  }
  for (long long i = n + 1; i <= 2 * n; ++i) {
    graf[i].push_back(e.size());
    e.push_back({{2 * n + 1, 1}, 0});
    graf[2 * n + 1].push_back(e.size());
    e.push_back({{i, 0}, 0});
  }
  long long res = 0;
  long long flow = 0;
  while (flow < n) {
    vector<long long> d(2 * n + 2, 2000000000000000001);
    vector<long long> p(2 * n + 2);
    d[0] = 0;
    for (long long i = 0; i < 2 * n + 2; ++i) {
      for (long long v = 0; v < 2 * n + 2; ++v) {
        for (auto i : graf[v]) {
          if (e[i].first.second == 0) {
            continue;
          }
          if (d[e[i].first.first] > d[v] + e[i].second) {
            d[e[i].first.first] = d[v] + e[i].second;
            p[e[i].first.first] = i;
          }
        }
      }
    }
    long long cur = 2 * n + 1;
    while (cur != 0) {
      long long i = p[cur];
      --e[i].first.second;
      ++e[i ^ 1].first.second;
      res += e[i].second;
      cur = e[i ^ 1].first.first;
    }
    ++flow;
  }
  cout << res;
}
signed main(signed argc, char **argv) {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  if (argc > 1 && (string)argv[1] == "local") {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
  }
  solve();
}
