#include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5 + 10;
const int MOD = (int)1e9 + 7;
const int oo = (int)1e9;
const int mm = 111111;
const int mn = 211;
int node, src, dest, edge;
int ver[mm], flow[mm], cost[mm], nex[mm];
int head[mn], dis[mn], p[mn], q[mn], vis[mn];
void prepare(int _node, int _src, int _dest) {
  node = _node, src = _src, dest = _dest;
  for (int i = 0; i < node; i++) head[i] = -1, vis[i] = 0;
  edge = 0;
}
void addedge(int u, int v, int f, int c) {
  ver[edge] = v, flow[edge] = f, cost[edge] = c, nex[edge] = head[u],
  head[u] = edge++;
  ver[edge] = u, flow[edge] = 0, cost[edge] = -c, nex[edge] = head[v],
  head[v] = edge++;
}
bool spfa() {
  int i, u, v, l, r = 0, tmp;
  for (i = 0; i < node; ++i) dis[i] = oo;
  dis[q[r++] = src] = 0;
  p[src] = p[dest] = -1;
  for (l = 0; l != r; (++l >= mn) ? l = 0 : l)
    for (i = head[u = q[l]], vis[u] = 0; i >= 0; i = nex[i])
      if (flow[i] && dis[v = ver[i]] > (tmp = dis[u] + cost[i])) {
        dis[v] = tmp;
        p[v] = i ^ 1;
        if (vis[v]) continue;
        vis[q[r++] = v] = 1;
        if (r >= mn) r = 0;
      }
  return p[dest] > -1;
}
int SpfaFlow() {
  int i, ret = 0, delta;
  while (spfa()) {
    for (i = p[dest], delta = oo; i >= 0; i = p[ver[i]])
      if (flow[i ^ 1] < delta) delta = flow[i ^ 1];
    for (i = p[dest]; i >= 0; i = p[ver[i]])
      flow[i] += delta, flow[i ^ 1] -= delta;
    ret += delta * dis[dest];
  }
  return ret;
}
int ma[55], mi[55];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) ma[i] = n, mi[i] = 1;
  for (int i = 1; i <= m; i++) {
    int op, l, r, x;
    scanf("%d%d%d%d", &op, &l, &r, &x);
    if (op == 1) {
      for (int i = l; i <= r; i++) mi[i] = max(mi[i], x);
    } else {
      for (int i = l; i <= r; i++) ma[i] = min(ma[i], x);
    }
  }
  int f = 1;
  prepare(n + n + 3, 0, n + n + 2);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      addedge(n + i, n + n + 1, 1, j + j - 1);
    }
  }
  addedge(n + n + 1, n + n + 2, oo, 0);
  for (int i = 1; i <= n; i++) {
    if (mi[i] > ma[i]) {
      f = 0;
      break;
    }
    addedge(0, i, 1, 0);
    for (int j = mi[i]; j <= ma[i]; j++) {
      addedge(i, n + j, 1, 0);
    }
  }
  if (!f)
    printf("-1\n");
  else {
    printf("%d\n", SpfaFlow());
  }
  return 0;
}
