#include <bits/stdc++.h>
using namespace std;
inline int read() {
  register int res = 0, c;
  while (c = getchar(), c < '0' || c > '9')
    ;
  do {
    res = (res << 3) + (res << 1) + (c ^ 48);
  } while (c = getchar(), '0' <= c && c <= '9');
  return res;
}
const int oo = 0x3f3f3f3f, maxn = 210, maxe = 12345;
int e = 1, to[maxe], ne[maxe], he[maxn], cap[maxe], cost[maxe];
int d[maxn], vis[maxn], ln[maxe], l, r, S, T, fl[maxn], inx, from[maxn];
int ans;
int n, m;
int upp[maxn], low[maxn];
void link(int x, int y, int v, int c) {
  to[++e] = y, ne[e] = he[x], he[x] = e, cap[e] = 0, cost[e] = c;
  to[++e] = x, ne[e] = he[y], he[y] = e, cap[e] = v, cost[e] = -c;
}
bool spfa() {
  memset(d, 127, sizeof(d));
  d[S] = 0, fl[S] = oo;
  for (vis[ln[l = r = 1] = S] = ++inx; l <= r; vis[ln[l++]] = 0) {
    for (int j = he[ln[l]]; j; j = ne[j])
      if (cap[j ^ 1] && d[to[j]] > d[ln[l]] + cost[j]) {
        d[to[j]] = d[ln[l]] + cost[j];
        fl[to[j]] = min(fl[ln[l]], cap[j ^ 1]);
        from[to[j]] = j;
        if (vis[to[j]] < inx) {
          vis[to[j]] = inx;
          ln[++r] = to[j];
        }
      }
  }
  if (d[T] >= 0x3f3f3f3f) return 0;
  int f = fl[T];
  ans += f * d[T];
  for (int t = T; t != S; t = to[from[t] ^ 1])
    cap[from[t]] += f, cap[from[t] ^ 1] -= f;
  return 1;
}
int main() {
  int N = read(), Q = read();
  S = 0, T = N + N + 1;
  for (int i = 1; i <= N; i++) upp[i] = N, low[i] = 1;
  for (int i = 1; i <= Q; i++) {
    int op = read(), l = read(), r = read(), h = read();
    if (op - 2)
      for (int i = l; i <= r; i++) low[i] = max(low[i], h);
    else
      for (int i = l; i <= r; i++) upp[i] = min(upp[i], h);
  }
  for (int i = 1; i <= N; i++)
    for (int j = 0; j < N; j++) link(S, i, 1, j << 1 | 1);
  for (int i = 1; i <= N; i++) {
    if (low[i] > upp[i]) {
      return puts("-1"), 0;
    }
    for (int j = low[i]; j <= upp[i]; j++) link(j, i + N, 1, 0);
    link(i + N, T, 1, 0);
  }
  ans = 0;
  while (spfa())
    ;
  printf("%d\n", ans);
  return 0;
}
