#include <bits/stdc++.h>
using namespace std;
const int maxn = 160;
const int maxM = (int)1e6 + 100;
const int mod = (int)1e9 + 7;
const int maxlog = (int)20;
const int P = mod;
int n, q, l[maxn], r[maxn], mx[maxn], mn[maxn], t[maxn], v[maxn], b[maxn],
    cnt[maxn], ans = INT_MAX, tot = 5000000, was[maxn], a[maxn];
int get() {
  for (int i = 1; i <= n; i++) cnt[a[i]]++;
  int res = 0;
  for (int i = 1; i <= n; i++) {
    res += cnt[i] * cnt[i];
  }
  return res;
}
int randint(int l, int r) {
  int v = (rand() << 15) ^ rand();
  v %= r - l + 1;
  return v + l;
}
int main() {
  srand(time(0));
  cin >> n >> q;
  if (q == 0) {
    cout << n;
    return 0;
  }
  for (int i = 1; i <= n; i++) {
    mn[i] = 1;
    mx[i] = n;
  }
  for (int i = 1; i <= q; i++) {
    cin >> t[i] >> l[i] >> r[i] >> v[i];
    for (int j = l[i]; j <= r[i]; j++) {
      if (t[i] == 2)
        mx[j] = min(mx[j], v[i]);
      else
        mn[j] = max(mn[j], v[i]);
    }
  }
  for (int i = 1; i <= n; i++) {
    if (mx[i] < mn[i]) {
      cout << -1;
      return 0;
    }
    a[i] = mn[i];
  }
  ans = get();
  int timer = 0;
  while (clock() / (double)CLOCKS_PER_SEC < 2.95) {
    memset(cnt, 0, sizeof(cnt));
    timer++;
    for (int i = 1; i <= n; i++) b[i] = a[i];
    int x = min(n, randint(1, max(1, n / 3)) + 1);
    for (int i = 1; i <= x; i++) {
      int pos = randint(1, n);
      while (was[pos] == timer) pos = randint(1, n);
      was[pos] = timer;
      a[pos] = randint(mn[pos], mx[pos]);
    }
    for (int i = 1; i <= n; i++) cnt[a[i]]++;
    int cur = 0;
    for (int i = 1; i <= n; i++) cur += cnt[i] * cnt[i];
    if (ans >= cur)
      ans = cur;
    else {
      for (int i = 1; i <= n; i++) a[i] = b[i];
    }
  }
  cout << ans;
}
