#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 10, MN = 202, ME = MN * MN;
int n;
bool adj[MN][MN], isinq[MN];
int q[MN], L, R, dist[MN];
int E, cap[ME], w[ME], from[ME], to[ME];
int par[MN];
int head[MN], prv[ME];
void Add(int s) {
  isinq[s] = true;
  q[R++] = s;
  if (R == MN) R = 0;
}
int Pop() {
  int ret = q[L++];
  isinq[ret] = false;
  if (L == MN) L = 0;
  return ret;
}
void add_edge(int u, int v, int Cap, int W) {
  from[E] = u, to[E] = v;
  prv[E] = head[u], cap[E] = Cap, w[E] = W;
  head[u] = E++;
  from[E] = v, to[E] = u;
  prv[E] = head[v], cap[E] = 0, w[E] = -W;
  head[v] = E++;
}
pair<int, int> mfmc(int st, int en) {
  fill(dist, dist + MN, INF);
  dist[st] = 0;
  Add(st);
  while (L ^ R) {
    int v = Pop();
    for (int e = head[v]; ~e; e = prv[e]) {
      int u = to[e];
      if (cap[e] && dist[v] + w[e] < dist[u]) {
        dist[u] = dist[v] + w[e];
        par[u] = e;
        if (!isinq[u]) Add(u);
      }
    }
  }
  int leg = dist[en];
  if (dist[en] >= INF) {
    return {0, 0};
  }
  int cur = en;
  while (cur ^ st) {
    int e = par[cur];
    cap[e] -= 1;
    cap[e ^ 1] += 1;
    cur = from[e];
  }
  pair<int, int> X = mfmc(st, en);
  return {X.first + leg, X.second + 1};
}
int main() {
  ios_base ::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  memset(head, -1, sizeof head), memset(prv, -1, sizeof prv);
  int q;
  cin >> n >> q;
  for (int i = 0; i < n; ++i) fill(adj[i], adj[i] + n, true);
  while (q--) {
    int tp, l, r, lim;
    cin >> tp >> l >> r >> lim;
    --l;
    for (int i = l; i < r; ++i) {
      if (tp == 1) {
        for (int j = lim - 2; ~j; --j) adj[j][i] = false;
      } else {
        for (int j = lim; j < n; ++j) adj[j][i] = false;
      }
    }
  }
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j)
      if (adj[i][j]) {
        add_edge(i + 1, j + n + 1, 1, 0);
      }
  for (int i = n + 1; i <= n + n; i++) add_edge(i, n + n + 1, 1, 0);
  for (int i = 1; i <= n; ++i) {
    int lst = 0;
    for (int num = 1; num <= n; ++num) {
      add_edge(0, i, 1, num * num - lst * lst);
      lst = num;
    }
  }
  pair<int, int> X = mfmc(0, n + n + 1);
  if (X.second != n) return cout << -1 << '\n', 0;
  cout << X.first << '\n';
  return 0;
}
