#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
const int oo = 1e9;
int n, m, q;
int l[maxn], r[maxn], dist[maxn], trace[maxn];
int c[maxn][maxn], d[maxn][maxn], f[maxn][maxn];
int getsign(int x) {
  if (x >= 0)
    return 1;
  else
    return -1;
}
bool findpath() {
  for (int i = 1; i <= m; i++) dist[i] = oo;
  dist[1] = 0;
  while (1) {
    bool stop = true;
    for (int i = 1; i <= m; i++)
      for (int j = 1; j <= m; j++)
        if (f[i][j] < c[i][j] &&
            dist[j] > dist[i] + d[i][j] * getsign(f[i][j])) {
          dist[j] = dist[i] + d[i][j] * getsign(f[i][j]);
          trace[j] = i;
          stop = false;
        }
    if (stop) break;
  }
  return dist[2] != oo;
}
void incflow() {
  int v = 2;
  while (v != 1) {
    int u = trace[v];
    if (d[u][v] != 0) {
      if (f[u][v] < 0) {
        d[u][v] -= 2;
        d[v][u] -= 2;
      } else {
        d[u][v] += 2;
        d[v][u] += 2;
      }
    }
    f[u][v]++;
    f[v][u]--;
    v = u;
  }
}
int main() {
  scanf("%d %d", &n, &q);
  for (int i = 1; i <= n; i++) {
    l[i] = 1;
    r[i] = n;
  }
  for (int i = 1; i <= q; i++) {
    int k, x, y, z;
    scanf("%d %d %d %d", &k, &x, &y, &z);
    for (int j = x; j <= y; j++)
      if (k == 1)
        l[j] = max(l[j], z);
      else
        r[j] = min(r[j], z);
  }
  for (int i = 1; i <= n; i++) {
    if (l[i] > r[i]) {
      printf("-1");
      return 0;
    }
    c[1][i + 2] = oo;
    d[1][i + 2] = 1;
    d[i + 2][1] = -1;
    for (int j = 1; j <= n; j++)
      if (i >= l[j] && i <= r[j]) c[i + 2][j + 2 + n] = 1;
    c[i + 2 + n][2] = 1;
  }
  m = 2 + n + n;
  int ans = 0;
  while (findpath()) incflow();
  for (int i = 1; i <= n; i++) ans += f[1][2 + i] * f[1][2 + i];
  printf("%d", ans);
  return 0;
}
