#include <bits/stdc++.h>
using namespace std;
int q, n, k, cnt, tot, S, T, ans, ff, mark[1010], dis[1010], head[1010],
    cur[1010], c[1010], w[1010];
map<int, int> id;
const int inf = 1e9;
struct edge {
  int from, to, next, v, c;
} e[200000];
struct leo {
  int l, r;
} a[1010];
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
inline void add_edge(int x, int y, int v, int c) {
  e[++cnt] = (edge){x, y, head[x], v, c};
  head[x] = cnt;
  e[++cnt] = (edge){y, x, head[y], 0, -c};
  head[y] = cnt;
}
inline bool spfa() {
  memset(mark, 0, sizeof(mark));
  for (int i = 0; i <= T; i++) dis[i] = inf;
  queue<int> q;
  dis[S] = 0;
  q.push(S);
  mark[S] = 1;
  while (!q.empty()) {
    int now = q.front();
    q.pop();
    for (int i = head[now]; i != -1; i = e[i].next) {
      int v1 = e[i].to;
      if (e[i].v && dis[v1] > dis[now] + e[i].c) {
        dis[v1] = dis[now] + e[i].c;
        cur[v1] = i;
        if (!mark[v1]) {
          q.push(v1);
          mark[v1] = 1;
        }
      }
    }
    mark[now] = 0;
  }
  return dis[T] != inf;
}
inline int mcf() {
  ans = 0;
  ff = 0;
  while (spfa()) {
    int flow = inf;
    for (int i = cur[T]; i; i = cur[e[i].from]) flow = min(flow, e[i].v);
    ans += flow * dis[T];
    ff += flow;
    for (int i = cur[T]; i; i = cur[e[i].from]) {
      e[i].v -= flow;
      e[i ^ 1].v += flow;
    }
  }
  return ff;
}
int main() {
  memset(head, -1, sizeof(head));
  memset(cur, 0, sizeof(cur));
  memset(c, 0, sizeof(c));
  cnt = 1;
  scanf("%d%d", &n, &q);
  for (int i = 1; i <= n; i++) a[i].l = 1, a[i].r = n;
  bool flag = true;
  for (int i = 1; i <= q; i++) {
    int t, l, r, v;
    scanf("%d%d%d%d", &t, &l, &r, &v);
    for (int j = l; j <= r; j++) {
      if (t == 1)
        a[j].l = max(a[j].l, v);
      else
        a[j].r = min(a[j].r, v);
      if (a[j].l > a[j].r) flag = false;
    }
  }
  if (!flag) {
    puts("-1");
    return 0;
  }
  S = 0;
  T = n + n + 1;
  for (int i = 1; i <= n; i++) {
    add_edge(S, i, 1, 0);
    for (int j = a[i].l; j <= a[i].r; j++) add_edge(i, j + n, 1, 0);
  }
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++) add_edge(i + n, T, 1, j + j - 1);
  int maxflow = mcf();
  if (maxflow != n) {
    puts("-1");
    return 0;
  }
  printf("%d\n", ans);
  return 0;
}
