#include <bits/stdc++.h>
using namespace std;
const int MAXN = 55;
const int MAXS = 10 * MAXN;
const int MAXM = MAXS * MAXS;
const int inf = 1e9;
struct Edge {
  int to, nxt, w, c;
};
int n, Q, cnt_e = 1, S, T;
int L[MAXN], R[MAXN];
int head[MAXS], curh[MAXS];
int dis[MAXS];
bool inq[MAXS];
Edge e[MAXM];
inline void addedge(int u, int v, int w, int c, bool fg) {
  e[++cnt_e].to = v;
  e[cnt_e].nxt = head[u];
  e[cnt_e].w = w;
  e[cnt_e].c = c;
  head[u] = cnt_e;
  if (fg) addedge(v, u, 0, -c, false);
}
inline bool spfa() {
  for (int i = 1; i <= 2 * n + 2; i++) curh[i] = head[i], dis[i] = inf;
  queue<int> q;
  dis[S] = 0;
  q.push(S);
  inq[S] = true;
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    inq[u] = false;
    for (int i = head[u]; i; i = e[i].nxt) {
      int v = e[i].to, w = e[i].w, c = e[i].c;
      if (!w || dis[u] + c >= dis[v]) continue;
      dis[v] = dis[u] + c;
      if (!inq[v]) q.push(v), inq[v] = true;
    }
  }
  return dis[T] != inf;
}
int cost = 0;
inline int dfs(int u, int flow) {
  if (!flow || u == T) return flow;
  int res = 0;
  inq[u] = true;
  for (int &i = curh[u]; i; i = e[i].nxt) {
    int v = e[i].to, w = e[i].w, c = e[i].c;
    if (!w || dis[v] != dis[u] + c || inq[v]) continue;
    int kkk = dfs(v, min(flow, w));
    e[i].w -= kkk;
    e[i ^ 1].w += kkk;
    flow -= kkk;
    res += kkk;
    cost += kkk * c;
    if (!flow) break;
  }
  inq[u] = false;
  return res;
}
inline int dinic() {
  int res = 0;
  while (spfa()) res += dfs(S, inf);
  return res;
}
int main() {
  scanf("%d%d", &n, &Q);
  for (int i = 1; i <= n; i++) L[i] = 1, R[i] = n;
  for (int i = 1; i <= Q; i++) {
    int op, l, r, v;
    scanf("%d%d%d%d", &op, &l, &r, &v);
    for (int j = l; j <= r; j++)
      if (op == 1)
        L[j] = max(L[j], v);
      else
        R[j] = min(R[j], v);
  }
  S = 2 * n + 1;
  T = 2 * n + 2;
  for (int i = 1; i <= n; i++) {
    if (L[i] > R[i]) {
      puts("-1");
      return 0;
    }
    addedge(S, i, 1, 0, true);
    for (int j = L[i]; j <= R[i]; j++) addedge(i, j + n, 1, 0, true);
    for (int j = 1; j <= n; j++) addedge(i + n, T, 1, 2 * j - 1, true);
  }
  dinic();
  printf("%d\n", cost);
  return 0;
}
