#include <bits/stdc++.h>
const int maxn = 10000;
const int inf = 1e9;
using namespace std;
struct Edge {
  int fr, to, cap, flow, cost;
};
struct MCMF {
  int n, m;
  vector<Edge> edges;
  vector<int> G[maxn + 5];
  int inq[maxn + 5], d[maxn + 5], p[maxn + 5], a[maxn + 5];
  void Init(int n) {
    for (int i = 0; i <= maxn; i++) G[i].clear();
    edges.clear();
  }
  void Addedge(int fr, int to, int cap, int cost) {
    edges.push_back((Edge){fr, to, cap, 0, cost});
    edges.push_back((Edge){to, fr, 0, 0, -cost});
    m = edges.size();
    G[fr].push_back(m - 2);
    G[to].push_back(m - 1);
  }
  bool Bell(int s, int t, int &flow, int &cost) {
    for (int i = 0; i <= maxn; i++) d[i] = inf;
    memset(inq, 0, sizeof(inq));
    d[s] = 0, inq[s] = 1, p[s] = 0, a[s] = inf;
    queue<int> Q;
    Q.push(s);
    while (!Q.empty()) {
      int u = Q.front();
      Q.pop();
      inq[u] = 0;
      for (int i = 0, l = G[u].size(); i < l; i++) {
        Edge &e = edges[G[u][i]];
        if (e.cap > e.flow && d[e.to] > d[u] + e.cost) {
          d[e.to] = d[u] + e.cost;
          p[e.to] = G[u][i];
          a[e.to] = min(a[u], e.cap - e.flow);
          if (!inq[e.to]) {
            Q.push(e.to);
            inq[e.to] = 1;
          }
        }
      }
    }
    if (d[t] == inf) return false;
    flow += a[t];
    cost += d[t] * a[t];
    int u = t;
    while (u != s) {
      edges[p[u]].flow += a[t];
      edges[p[u] ^ 1].flow -= a[t];
      u = edges[p[u]].fr;
    }
    return true;
  }
  int Mincost(int s, int t, int N) {
    int flow = 0, cost = 0;
    while (Bell(s, t, flow, cost))
      ;
    if (flow < N) cost = -1;
    return cost;
  }
} my;
int n, m, S, T;
int l[105], r[105];
int main() {
  while (~scanf("%d %d", &n, &m)) {
    for (int i = 1; i <= n; i++) l[i] = 1, r[i] = n;
    for (int i = 1; i <= m; i++) {
      int t, x, y, v;
      scanf("%d %d %d %d", &t, &x, &y, &v);
      if (t == 1)
        for (int j = x; j <= y; j++) l[j] = max(l[j], v);
      if (t == 2)
        for (int j = x; j <= y; j++) r[j] = min(r[j], v);
    }
    S = 0, T = n * 2 + 1;
    my.Init(n * 2 + 1);
    for (int i = 1; i <= n; i++) {
      for (int j = l[i]; j <= r[i]; j++) {
        my.Addedge(j, i + n, 1, 0);
      }
      my.Addedge(i + n, T, 1, 0);
    }
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= n; j++) {
        int cost = j * 2 - 1;
        my.Addedge(S, i, 1, cost);
      }
    }
    int cost = my.Mincost(S, T, n);
    printf("%d\n", cost);
  }
  return 0;
}
