#include <bits/stdc++.h>
using namespace std;
const int N = 550;
const int INF = 1000000000;
int n, m, L[N], R[N], S, T, dis[N], f[N], pre[N], cnt, vis[N];
struct edge {
  int v, f, w;
  edge *next, *rev;
} pool[N * N], *head[N * 2], *r[N * 2];
inline void addedge(int u, int v, int f, int w) {
  edge *p = &pool[++cnt], *q = &pool[++cnt];
  p->v = v, p->f = f, p->w = w, p->next = head[u], head[u] = p;
  p->rev = q;
  q->v = u, q->f = 0, q->w = -w, q->next = head[v], head[v] = q;
  q->rev = p;
}
inline bool spfa() {
  for (int i = S; i <= T; i++)
    pre[i] = -1, dis[i] = INF, r[i] = NULL, vis[i] = 0;
  queue<int> Q;
  Q.push(S), dis[S] = 0, vis[S] = 1;
  f[S] = INF;
  while (!Q.empty()) {
    int u = Q.front(), v;
    Q.pop();
    vis[u] = 0;
    for (edge *p = head[u]; p; p = p->next) {
      if (p->f && dis[v = p->v] > dis[u] + p->w) {
        dis[v] = dis[u] + p->w;
        pre[v] = u, r[v] = p;
        f[v] = min(f[u], p->f);
        if (!vis[v]) vis[v] = 1, Q.push(v);
      }
    }
  }
  return pre[T] != -1;
}
int MF;
int MC;
inline void MCMF() {
  while (spfa()) {
    for (int i = T; i != S; i = pre[i]) r[i]->f -= f[T], r[i]->rev->f += f[T];
    MF += f[T], MC += dis[T] * f[T];
  }
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; i++) L[i] = 1, R[i] = n;
  for (int i = 1; i <= m; i++) {
    int op, l, r, v;
    scanf("%d %d %d %d", &op, &l, &r, &v);
    if (op == 1)
      for (int j = l; j <= r; j++) L[j] = max(L[j], v);
    else
      for (int j = l; j <= r; j++) R[j] = min(R[j], v);
  }
  for (int i = 1; i <= n; i++) {
    if (L[i] > R[i]) {
      printf("-1\n");
      return 0;
    }
  }
  S = 0, T = n + n + 1;
  for (int i = 1; i <= n; i++) {
    addedge(S, i, 1, 0);
    for (int j = L[i]; j <= R[i]; j++) addedge(i, j + n, INF, 0);
    for (int j = 1; j <= n; j++) {
      addedge(i + n, T, 1, j * 2 - 1);
    }
  }
  MCMF();
  printf("%d\n", MC);
  return 0;
}
