#include <bits/stdc++.h>
using namespace std;
struct Edge {
  int u, v, cap, flow, cost;
  Edge(int a, int b, int c, int d, int f)
      : u(a), v(b), cap(c), cost(d), flow(f){};
};
struct EdmosKarp {
  int n, m;
  vector<Edge> edges;
  vector<int> G[200];
  int inq[200];
  int d[200];
  int a[200];
  int p[200];
  void init(int n) {
    this->n = n;
    for (int i = 1; i <= n; i++) G[i].clear();
    edges.clear();
  }
  void AddEdge(int from, int to, int cap, int flow, int cost) {
    G[from].push_back(edges.size());
    edges.push_back(Edge(from, to, cap, cost, 0));
    G[to].push_back(edges.size());
    edges.push_back(Edge(to, from, 0, -cost, 0));
  }
  bool BellmanFord(int s, int t, int& flow, int& cost) {
    memset(d, 0x3f3f3f3f, sizeof(d));
    memset(inq, 0, sizeof(inq));
    d[s] = 0;
    a[s] = 0x3f3f3f3f;
    queue<int> q;
    q.push(s);
    while (!q.empty()) {
      int x = q.front();
      q.pop();
      inq[x] = 0;
      for (int i = 0; i < G[x].size(); i++) {
        Edge& e = edges[G[x][i]];
        if (e.cap > e.flow && d[e.v] > d[e.u] + e.cost) {
          d[e.v] = d[e.u] + e.cost;
          p[e.v] = G[x][i];
          a[e.v] = min(a[x], e.cap - e.flow);
          if (!inq[e.v]) {
            inq[e.v] = 1;
            q.push(e.v);
          }
        }
      }
    }
    if (d[t] == 0x3f3f3f3f) return false;
    flow += a[t];
    cost += (long long)d[t] * (long long)a[t];
    for (int u = t; u != s; u = edges[p[u]].u) {
      edges[p[u]].flow += a[t];
      edges[p[u] ^ 1].flow -= a[t];
    }
    return true;
  }
  int MincostMaxflow(int s, int t, int& cost) {
    int flow = 0;
    while (BellmanFord(s, t, flow, cost))
      ;
    return flow;
  }
} solver;
int down[200], up[200];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    down[i] = 1;
    up[i] = n;
  }
  for (int i = 1; i <= m; i++) {
    int op, l, r, v;
    scanf("%d%d%d%d", &op, &l, &r, &v);
    if (op == 1) {
      for (int j = l; j <= r; j++) down[j] = max(down[j], v);
    } else {
      for (int j = l; j <= r; j++) {
        up[j] = min(up[j], v);
      }
    }
  }
  int s = 2 * n + 1, t = 2 * n + 2;
  for (int i = 1; i <= n; i++) {
    solver.AddEdge(s, i, 1, 0, 0);
    for (int j = down[i]; j <= up[i]; j++) {
      solver.AddEdge(i, j + n, 1, 0, 0);
    }
  }
  for (int i = n + 1; i <= n * 2; i++) {
    for (int j = 1; j <= 50; j++) {
      solver.AddEdge(i, t, 1, 0, j * 2 - 1);
    }
  }
  int cost = 0;
  int flow = solver.MincostMaxflow(s, t, cost);
  if (flow != n)
    puts("-1");
  else
    printf("%d\n", cost);
}
