#include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 10;
const int M = 1000000007;
const double PI = atan(1) * 4;
const int oo = 1000000000;
int n, q, match[51], fr[51], vis[51], vs;
bool is[51];
pair<int, int> lm[51];
bool get(int u) {
  vis[u] = vs;
  for (int i = lm[u].first; i <= lm[u].second; ++i) {
    if (match[i] == -1) {
      match[i] = u;
      ++fr[i];
      return true;
    }
  }
  for (int i = lm[u].first; i <= lm[u].second; ++i) {
    if (match[i] != -1 && vis[match[i]] != vs && get(match[i])) {
      match[i] = u;
      return true;
    }
  }
  return false;
}
int go() {
  memset(fr, 0, sizeof(fr));
  memset(is, 0, sizeof(is));
  while (true) {
    memset(match, -1, sizeof(match));
    bool f = 1;
    for (int i = 0; i < n; ++i) {
      ++vs;
      if (!is[i] && !get(i))
        f = 0;
      else
        is[i] = true;
    }
    if (f) break;
  }
  int ans = 0;
  for (int i = 1; i <= n; ++i) ans += fr[i] * fr[i];
  return ans;
}
int main() {
  cin >> n >> q;
  for (int i = 0; i < n; ++i) {
    lm[i].second = n;
    lm[i].first = 1;
  }
  for (int a, b, c, d, i = 0; i < q; ++i) {
    cin >> a >> b >> c >> d;
    --b;
    --c;
    if (a == 1) {
      for (int j = b; j <= c; ++j) lm[j].first = max(lm[j].first, d);
    } else {
      for (int j = b; j <= c; ++j) lm[j].second = min(lm[j].second, d);
    }
  }
  for (int i = 0; i < n; ++i)
    if (lm[i].first > lm[i].second) return cout << -1, 0;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < n - 1; ++j)
      if (lm[j].second - lm[j].first > lm[j + 1].second - lm[j + 1].first)
        swap(lm[j], lm[j + 1]);
  int ans = go();
  for (int i = 0; i < 500; ++i) {
    random_shuffle(lm, lm + n);
    ans = min(ans, go());
  }
  cout << ans << endl;
}
