#include <bits/stdc++.h>
using namespace std;
const int N = 105;
struct mincost {
  int s, t, d[N], f[N], prev[N];
  bool inQ[N];
  vector<int> G[N];
  mincost(int s = 0, int t = 0) : s(s), t(t){};
  struct edge {
    int u, v, c, f, cost, rev;
    edge(int u, int v, int c, int cost, int rev)
        : u(u), v(v), c(c), cost(cost), rev(rev) {
      f = 0;
    };
  };
  vector<edge> e;
  void addEdge(int u, int v, int c, int cost) {
    G[u].push_back(e.size());
    e.push_back(edge(u, v, c, cost, e.size() + 1));
    G[v].push_back(e.size());
    e.push_back(edge(v, u, 0, -cost, e.size() - 1));
  }
  bool bfs() {
    memset(d, 63, sizeof(d));
    memset(inQ, false, sizeof(inQ));
    memset(f, 0, sizeof(f));
    memset(prev, -1, sizeof(prev));
    queue<int> q;
    q.push(s);
    d[s] = 0;
    inQ[s] = true;
    f[s] = 1061109567;
    while (!q.empty()) {
      int u = q.front();
      q.pop();
      inQ[u] = false;
      for (auto i : G[u]) {
        int v = e[i].v;
        if (d[v] > d[u] + e[i].cost && e[i].f < e[i].c) {
          d[v] = d[u] + e[i].cost;
          prev[v] = i;
          f[v] = min(f[u], e[i].c - e[i].f);
          if (!inQ[v]) {
            q.push(v);
            inQ[v] = true;
          }
        }
      }
    }
    return d[t] != 1061109567;
  }
  pair<int, int> get() {
    int flow = 0, cost = 0;
    while (bfs()) {
      int val = f[t];
      flow += val;
      cost += val * d[t];
      int cur = t;
      while (cur != s) {
        int id = prev[cur];
        e[id].f += val;
        e[e[id].rev].f -= val;
        cur = e[id].u;
      }
    }
    return pair<int, int>(flow, cost);
  }
} mf;
int mn[51], mx[51];
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, q;
  cin >> n >> q;
  for (int i = 1; i < n + 1; i++) mn[i] = 1, mx[i] = n;
  while (q--) {
    int l, r, x, type;
    cin >> type >> l >> r >> x;
    if (type == 1)
      for (int i = l; i < r + 1; i++) mn[i] = max(x, mn[i]);
    else
      for (int i = l; i < r + 1; i++) mx[i] = min(mx[i], x);
  }
  mf = mincost(0, 2 * n + 1);
  for (int i = 1; i < n + 1; i++) {
    mf.addEdge(0, i, 1, 0);
    for (int val = mn[i]; val < mx[i] + 1; val++) mf.addEdge(i, val + n, 1, 0);
    for (int j = 1; j < n + 1; j++) mf.addEdge(i + n, 2 * n + 1, 1, 2 * j - 1);
  }
  pair<int, int> temp = mf.get();
  if (temp.first != n)
    cout << "-1";
  else
    cout << temp.second;
  return 0;
}
