#include <bits/stdc++.h>
using namespace std;
const int N = 105;
const int inf = 1000 * 1000 * 1000;
const int mod = 1000 * 1000 * 1000 + 7;
struct edge {
  int to, cap, flow, cost;
};
int S, T;
vector<edge> G;
vector<int> g[N];
int mn[N], mx[N], p[N], qan[N];
string s;
int n, q;
int mas[N], id[N], ind[N], parent[N], d[N];
void add_edge(int a, int b, int c, int val) {
  edge e1 = {b, c, 0, val};
  edge e2 = {a, 0, 0, -val};
  g[a].push_back((int)G.size());
  G.push_back(e1);
  g[b].push_back((int)G.size());
  G.push_back(e2);
}
bool fb() {
  for (int i = 0; i <= T; i++) d[i] = inf;
  d[S] = 0;
  while (true) {
    bool flag = false;
    for (int i = 0; i <= T; i++) {
      for (int j = 0; j < (int)g[i].size(); j++) {
        edge e = G[g[i][j]];
        if (e.cap == e.flow) continue;
        int to = e.to;
        if (d[i] + e.cost < d[to]) {
          d[to] = d[i] + e.cost;
          parent[to] = i;
          ind[to] = j;
          flag = true;
        }
      }
    }
    if (!flag) break;
  }
  return (d[T] != inf);
}
int flow() {
  int flow = 0;
  int answ = 0;
  while (fb()) {
    int addflow = inf;
    for (int v = T; v != S; v = parent[v]) {
      int pp = parent[v];
      int ii = ind[v];
      addflow = min(addflow, G[g[pp][ii]].cap - G[g[pp][ii]].flow);
    }
    for (int v = T; v != S; v = parent[v]) {
      int pp = parent[v];
      int ii = ind[v];
      G[g[pp][ii]].flow += addflow;
      G[g[pp][ii] ^ 1].flow -= addflow;
      answ += G[g[pp][ii]].cost * addflow;
    }
    flow += addflow;
  }
  return answ;
}
int main() {
  cin >> n >> q;
  for (int i = 1; i <= n; i++) {
    mn[i] = 1;
    mx[i] = n;
  }
  while (q--) {
    int id, l, r, v;
    cin >> id >> l >> r >> v;
    if (id == 1) {
      for (int i = l; i <= r; i++) mn[i] = max(mn[i], v);
    } else {
      for (int i = l; i <= r; i++) mx[i] = min(mx[i], v);
    }
  }
  for (int i = 1; i <= n; i++) {
    if (mn[i] > mx[i]) {
      cout << -1 << endl;
      return 0;
    }
  }
  S = 0;
  T = 2 * n + 1;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      add_edge(S, i, 1, 2 * j - 1);
    }
    for (int j = 1; j <= n; j++) {
      if (i >= mn[j] && i <= mx[j]) {
        add_edge(i, j + n, 1, 0);
      }
    }
    add_edge(i + n, T, 1, 0);
  }
  cout << flow() << endl;
  return 0;
}
