#include <bits/stdc++.h>
using namespace std;
namespace mincost {
const int V = 1000, E = 1000000, inf = 1e9;
int dis[V], q[V * 300], vis[V], fst[V], pre[V], nxt[E], second[E], f[E], c[E],
    S, T, flow, cost, tot, tn;
void init(int s, int t, int Tn) {
  tot = 1;
  tn = Tn;
  for (int(i) = (0); (i) < (tn); (i)++) fst[i] = 0;
  S = s;
  T = t;
}
void add(int u, int v, int ff, int cc) {
  tot++;
  second[tot] = v;
  nxt[tot] = fst[u];
  f[tot] = ff;
  c[tot] = cc;
  fst[u] = tot;
  tot++;
  second[tot] = u;
  nxt[tot] = fst[v];
  f[tot] = 0;
  c[tot] = -cc;
  fst[v] = tot;
}
bool spfa() {
  for (int(i) = (0); (i) < (tn); (i)++) dis[i] = inf, vis[i] = 0, pre[i] = 0;
  dis[S] = 0;
  q[0] = S;
  vis[S] = 1;
  int t = 1;
  for (int(i) = (0); (i) < (t); (i)++) {
    int u = q[i];
    for (int j = fst[u]; j; j = nxt[j]) {
      int v = second[j];
      if (f[j] && dis[v] > dis[u] + c[j]) {
        dis[v] = dis[u] + c[j];
        pre[v] = j;
        if (!vis[v]) vis[v] = 1, q[t++] = v;
      }
    }
    vis[u] = 0;
  }
  return dis[T] != inf;
}
void augment() {
  int p = T, _f = inf;
  while (pre[p]) _f = min(_f, f[pre[p]]), p = second[pre[p] ^ 1];
  flow += _f;
  cost += _f * dis[T];
  p = T;
  while (pre[p]) f[pre[p]] -= _f, f[pre[p] ^ 1] += _f, p = second[pre[p] ^ 1];
}
void solve() {
  flow = 0, cost = 0;
  while (spfa()) augment();
}
}  // namespace mincost
int n, q, menor[55], maior[55];
int main() {
  scanf("%d%d", &n, &q);
  for (int(i) = (0); (i) < (n); (i)++) menor[i] = 1, maior[i] = n;
  for (int(i) = (0); (i) < (q); (i)++) {
    int tp, l, r, v;
    scanf("%d%d%d%d", &tp, &l, &r, &v);
    l--;
    for (int(j) = (l); (j) < (r); (j)++) {
      if (tp == 1)
        menor[j] = max(menor[j], v);
      else
        maior[j] = min(maior[j], v);
    }
  }
  int s = 1, t = n + n + 2;
  mincost::init(s, t, t + 1);
  for (int(i) = (0); (i) < (n); (i)++) {
    mincost::add(s, 2 + i, 1, 0);
    for (int(j) = (menor[i] - 1); (j) < (maior[i]); (j)++)
      mincost::add(2 + i, 2 + n + j, 1, 0);
  }
  for (int(i) = (0); (i) < (n); (i)++) {
    int pr = 1;
    for (int(j) = (0); (j) < (n); (j)++) {
      mincost::add(2 + n + i, t, 1, pr);
      pr += 2;
    }
  }
  mincost::solve();
  if (mincost::flow < n)
    puts("-1");
  else
    printf("%d\n", mincost::cost);
}
