#include <bits/stdc++.h>
using namespace std;
template <class T>
void read(T &x) {
  x = 0;
  bool flag = 0;
  char ch = getchar();
  for (; ch < '0' || ch > '9'; ch = getchar()) flag |= ch == '-';
  for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - 48;
  flag ? x = ~x + 1 : 0;
}
int S, T, flow, cost, head[150], tot = 1, dis[150], pre[150];
;
struct edge {
  int u, v, c, w, next;
} e[100001];
queue<int> q;
bool inq[150];
inline void insert(int u, int v, int c, int w) {
  e[++tot].u = u, e[tot].v = v, e[tot].c = c, e[tot].w = w,
  e[tot].next = head[u], head[u] = tot;
}
inline void add(int u, int v, int c, int w) {
  insert(u, v, c, w), insert(v, u, 0, -w);
}
inline bool spfa() {
  for (int i = (S); i <= (T); i++) dis[i] = 0x3f3f3f3f;
  dis[S] = 0;
  q.push(S);
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    inq[u] = 0;
    for (int i = head[u], v, w; i; i = e[i].next)
      if (e[i].c > 0 && dis[v = e[i].v] > dis[u] + (w = e[i].w)) {
        dis[v] = dis[u] + w, pre[v] = i;
        if (!inq[v]) q.push(v);
        inq[v] = 1;
      }
  }
  return dis[T] != 0x3f3f3f3f;
}
inline void mcf() {
  int d = 0x3f3f3f3f;
  for (int i = T; (i ^ S); i = e[pre[i]].u) d = min(d, e[pre[i]].c);
  flow += d;
  for (int i = T; (i ^ S); i = e[pre[i]].u)
    e[pre[i]].c -= d, e[pre[i] ^ 1].c += d, cost += d * e[pre[i]].w;
}
int L[150], R[150];
int main() {
  int n, q;
  read(n), read(q);
  memset(L, 0xc0, sizeof L), memset(R, 0x3f, sizeof R);
  T = 2 * n + 1;
  for (int i = (1); i <= (n); i++) {
    for (int j = (1); j <= (n); j++) add(S, i, 1, j * 2 - 1);
    add(i + n, T, 1, 0);
  }
  while (q--) {
    int op, l, r, v;
    read(op), read(l), read(r), read(v);
    for (int i = (l); i <= (r); i++)
      op == 1 ? L[i] = max(L[i], v) : R[i] = min(R[i], v);
  }
  for (int i = (1); i <= (n); i++)
    for (int j = (1); j <= (n); j++)
      if (i >= L[j] && i <= R[j]) add(i, j + n, 1, 0);
  while (spfa()) mcf();
  printf("%d", flow == n ? cost : -1);
  return 0;
}
