#include <bits/stdc++.h>
using namespace std;
struct Edge {
  int to, cap, cost, next;
};
Edge E[23456];
int head[105], ne = 1;
inline void addEdge(int from, int to, int cap, int cost) {
  E[++ne] = {to, cap, cost, head[from]}, head[from] = ne;
  E[++ne] = {from, 0, -cost, head[to]}, head[to] = ne;
}
int d[105], p[105];
bool inqueue[105];
pair<int, int> mcmf(int S, int T) {
  int f = 0, c = 0;
  while (1) {
    for (int i = S; i <= T; ++i) d[i] = 1e9;
    queue<int> Q;
    Q.push(S);
    d[S] = 0;
    while (!Q.empty()) {
      auto v = Q.front();
      Q.pop();
      inqueue[v] = 0;
      for (int x = head[v]; x; x = E[x].next) {
        int &u = E[x].to, &cap = E[x].cap, &cost = E[x].cost;
        if (cap > 0 and d[v] + cost < d[u]) {
          d[u] = d[v] + cost;
          p[u] = x;
          if (!inqueue[u]) Q.push(u), inqueue[u] = 1;
        }
      }
    }
    if (d[T] == 1e9) break;
    int df = 1e9;
    for (int i = T; i != S; i = E[p[i] ^ 1].to) df = min(df, E[p[i]].cap);
    for (int i = T; i != S; i = E[p[i] ^ 1].to)
      E[p[i]].cap -= df, E[p[i] ^ 1].cap += df;
    f += df, c += df * d[T];
  }
  return {f, c};
}
int L[55], U[55];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, q;
  cin >> n >> q;
  for (int i = 1; i <= n; ++i) L[i] = 1, U[i] = n;
  for (int i = 0; i < q; ++i) {
    int t, l, r, v;
    cin >> t >> l >> r >> v;
    for (int j = l; j <= r; ++j) {
      if (t == 1)
        L[j] = max(L[j], v);
      else
        U[j] = min(U[j], v);
    }
  }
  int S = 0, T = n + n + 1;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= n; ++j) addEdge(S, i, 1, 2 * j - 1);
  for (int i = 1; i <= n; ++i)
    for (int j = L[i]; j <= U[i]; ++j) addEdge(j, i + n, 1, 0);
  for (int i = 1; i <= n; ++i) addEdge(i + n, T, 1, 0);
  auto ans = mcmf(S, T);
  if (ans.first == n)
    cout << ans.second << endl;
  else
    cout << -1 << endl;
  return 0;
}
