#include <bits/stdc++.h>
using namespace std;
template <typename TP>
inline bool rd(TP& r) {
  r = 0;
  char tmp = getchar();
  while (tmp < '0' || tmp > '9') {
    if (tmp == EOF) return 0;
    tmp = getchar();
  }
  while ('0' <= tmp && tmp <= '9') {
    r = (r << 3) + (r << 1) + tmp - '0';
    tmp = getchar();
  }
  return 1;
}
int n, op;
int up[200], dn[200];
int h[200 * 2], t[40000], x[40000], c[40000], tot = 1;
long long z[40000];
void ade(int u, int v, int cc, long long zz) {
  tot++;
  x[tot] = h[u];
  h[u] = tot;
  t[tot] = v;
  z[tot] = zz;
  c[tot] = cc;
}
void add(int u, int v, int cc, long long zz) {
  ade(u, v, cc, zz);
  ade(v, u, 0, -zz);
}
int most[200 * 2];
long long ans = 0;
struct sta {
  int po;
  long long cst;
  sta(int pp = 0, long long cost = 0) {
    po = pp;
    cst = cost;
  }
  friend bool operator>(sta a, sta b) { return a.cst < b.cst; }
  friend bool operator<(sta a, sta b) { return a.cst > b.cst; }
};
priority_queue<sta> q;
bool vis[200 * 2];
long long d[200 * 2];
int pre[200 * 2];
bool find() {
  while (!q.empty()) q.pop();
  memset(vis, 0, sizeof(vis));
  memset(d, 0x3f, sizeof(d));
  q.push(sta(0, 0));
  d[0] = 0;
  int now;
  while (!q.empty()) {
    now = q.top().po;
    q.pop();
    if (vis[now]) continue;
    vis[now] = 1;
    if (now == 190) return 1;
    for (int j = h[now]; j; j = x[j])
      if (c[j] > 0 && !vis[t[j]] && d[t[j]] > d[now] + z[j]) {
        d[t[j]] = d[now] + z[j];
        pre[t[j]] = j;
        q.push(sta(t[j], d[t[j]]));
      }
  }
  return 0;
}
long long more() {
  int now = 190;
  int mn = 234567;
  while (now != 0) {
    mn = min(mn, c[pre[now]]);
    now = t[pre[now] ^ 1];
  }
  now = 190;
  long long re = 0;
  while (now != 0) {
    re += z[pre[now]] * mn;
    c[pre[now]] -= mn;
    c[pre[now] ^ 1] += mn;
    now = t[pre[now] ^ 1];
  }
  return re;
}
bool FLOW() {
  if (!find()) return 0;
  while (find()) {
    ans += more();
  }
  return 1;
}
int main() {
  rd(n), rd(op);
  int t, l, r, v;
  for (int i = 1; i <= n; i++) up[i] = 50, dn[i] = 1;
  for (int i = 1; i <= op; i++) {
    rd(t), rd(l), rd(r), rd(v);
    if (t == 1)
      for (int j = l; j <= r; j++) dn[j] = max(dn[j], v);
    else if (t == 2)
      for (int j = l; j <= r; j++) up[j] = min(up[j], v);
  }
  for (int i = 1; i <= n; i++) {
    if (dn[i] > up[i]) {
      printf("-1\n");
      return 0;
    }
    add(0, i, 1, 0);
    for (int j = dn[i]; j <= up[i]; j++) {
      add(i, j + n, 1, 0);
      most[j]++;
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= most[i]; j++)
      add(i + n, 190, 1, j * j - (j - 1) * (j - 1));
  }
  if (!FLOW()) {
    printf("-1\n");
    return 0;
  }
  printf("%I64d\n", ans);
  return 0;
}
