#include <bits/stdc++.h>
using namespace std;
struct Edge {
  int to, cost, cap, rev;
};
vector<Edge> g[150];
int h[150], dist[150], prevv[150], preve[150];
inline void addEdge(int u, int v, int cap, int cost) {
  g[u].push_back({v, cost, cap, (int)g[v].size()});
  g[v].push_back({u, -cost, 0, (int)g[u].size() - 1});
}
int MCMF(int source, int sink, int flow) {
  memset(h, 0, sizeof h);
  int res = 0;
  while (flow > 0) {
    memset(dist, 0x3f, sizeof dist);
    dist[source] = 0;
    priority_queue<pair<int, int>, vector<pair<int, int> >,
                   greater<pair<int, int> > >
        pq;
    pq.push(pair<int, int>(0, source));
    while (!pq.empty()) {
      int now = pq.top().first, u = pq.top().second;
      pq.pop();
      if (dist[u] < now) continue;
      for (int i = 0; i < (int)g[u].size(); i++) {
        Edge& e = g[u][i];
        if (e.cap > 0 && dist[e.to] > dist[u] + e.cost + h[u] - h[e.to]) {
          dist[e.to] = dist[u] + e.cost + h[u] - h[e.to];
          prevv[e.to] = u;
          preve[e.to] = i;
          pq.push(pair<int, int>(dist[e.to], e.to));
        }
      }
    }
    if (dist[sink] == 0x3f3f3f3f) return -1;
    for (int i = source; i <= sink; i++) h[i] += dist[i];
    int d = flow;
    for (int i = sink; i != source; i = prevv[i])
      d = min(d, g[prevv[i]][preve[i]].cap);
    res += d * h[sink];
    flow -= d;
    for (int i = sink; i != source; i = prevv[i]) {
      g[prevv[i]][preve[i]].cap -= d;
      g[i][g[prevv[i]][preve[i]].rev].cap += d;
    }
  }
  return res;
}
int L[55], R[55];
int main() {
  int n, q, t, l, r, v;
  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++) {
    scanf("%d%d%d%d", &t, &l, &r, &v);
    if (t == 1) {
      for (int j = l; j <= r; j++) L[j] = max(L[j], v);
    } else {
      for (int j = l; j <= r; j++) R[j] = min(R[j], v);
    }
  }
  bool no_solution = false;
  for (int i = 1; i <= n; i++) {
    if (L[i] > R[i]) {
      no_solution = true;
    }
  }
  if (no_solution)
    puts("-1");
  else {
    int source = 0, sink = 2 * n + 1;
    for (int i = 1; i <= n; i++) {
      addEdge(source, i, 1, 0);
      for (int j = L[i]; j <= R[i]; j++) {
        addEdge(i, j + n, 1, 0);
      }
      for (int j = 1; j <= n; j++) {
        addEdge(i + n, sink, 1, j * j - (j - 1) * (j - 1));
      }
    }
    printf("%d\n", MCMF(source, sink, n));
  }
  return 0;
}
