#include <bits/stdc++.h>
using namespace std;
const int oo = 1e9;
queue<int> Q;
bool vis[105];
int num, cur[105], vet[200005], nex[200005], val[200005], cost[200005],
    head[105];
int n, m, S, T, minn[105], maxx[105], q[200005], pre[105], preedge[105],
    dis[105];
void addedge(int u, int v, int l, int c) {
  num++;
  vet[num] = v;
  val[num] = l;
  cost[num] = c;
  nex[num] = head[u];
  head[u] = num;
}
void add(int u, int v, int l, int c) {
  addedge(u, v, l, c);
  addedge(v, u, 0, -c);
}
bool spfa() {
  memset(vis, 0, sizeof(vis));
  for (int i = 1; i <= T; i++) dis[i] = oo;
  while (!Q.empty()) Q.pop();
  Q.push(S);
  vis[S] = 1;
  dis[S] = 0;
  while (!Q.empty()) {
    int u = Q.front();
    vis[u] = 0;
    Q.pop();
    for (int i = head[u]; i; i = nex[i]) {
      if (val[i] <= 0) continue;
      int v = vet[i];
      if (dis[u] + cost[i] < dis[v]) {
        dis[v] = dis[u] + cost[i];
        pre[v] = u;
        preedge[v] = i;
        if (!vis[v]) {
          Q.push(v);
          vis[v] = 1;
        }
      }
    }
  }
  return dis[T] < oo;
}
int dinic() {
  int ans = 0;
  while (spfa()) {
    int x = T;
    ans += dis[T];
    while (x != S) {
      val[preedge[x]]--;
      val[preedge[x] ^ 1]++;
      x = pre[x];
    }
  }
  return ans;
}
int main() {
  int n, q;
  scanf("%d%d", &n, &q);
  S = 0;
  T = n + n + 1;
  for (int i = 1; i <= n; i++) minn[i] = 1, maxx[i] = n;
  for (int i = 1; i <= q; i++) {
    int t, x, y, v;
    scanf("%d%d%d%d", &t, &x, &y, &v);
    if (t == 1)
      for (int j = x; j <= y; j++) minn[j] = max(minn[j], v);
    else
      for (int j = x; j <= y; j++) maxx[j] = min(maxx[j], v);
  }
  for (int i = 1; i <= n; i++) {
    if (maxx[i] < minn[i]) {
      printf("-1\n");
      return 0;
    }
  }
  num = 1;
  for (int i = 1; i <= n; i++) add(S, i, 1, 0);
  for (int i = 1; i <= n; i++)
    for (int j = minn[i]; j <= maxx[i]; j++) add(i, j + n, 1, 0);
  for (int i = n + 1; i <= n + n; i++) {
    for (int j = 1; j <= n; j++) {
      add(i, T, 1, j * j - (j - 1) * (j - 1));
    }
  }
  printf("%d\n", dinic());
}
