#include <bits/stdc++.h>
using namespace std;
template <typename T>
void printRange(T &x) {
  for (auto y : x) cout << y << ' ';
  cout << endl;
}
const int V = 105;
const int E = 5e4 + 10;
const int INF = 1e6;
int ub[V], lb[V];
int n, q;
struct edge {
  int from, to, cap, we, flow;
};
edge ed[E];
vector<int> g[V];
int dist[V];
int par[V];
int eu[V];
bool vis[V];
int curr = 0;
int s, t;
queue<int> qu;
void add_edge(int from, int to, int cap, int we) {
  edge x;
  x.from = from, x.to = to, x.cap = cap, x.we = we, x.flow = 0;
  ed[curr] = x;
  swap(x.from, x.to);
  x.we = -x.we;
  x.cap = 0;
  g[from].push_back(curr++);
  ed[curr] = x;
  g[to].push_back(curr++);
}
long long flow() {
  long long ans = 0;
  for (int i = (0); i < (n); ++i) {
    fill(dist, dist + t + 1, INF);
    fill(par, par + t + 1, -1);
    fill(eu, eu + t + 1, -1);
    fill(vis, vis + t + 1, 0);
    qu.push(s);
    dist[s] = 0;
    while (!qu.empty()) {
      int fr = qu.front();
      vis[fr] = false;
      qu.pop();
      for (auto y : g[fr]) {
        if (ed[y].flow == ed[y].cap) continue;
        if (dist[ed[y].to] > dist[fr] + ed[y].we) {
          dist[ed[y].to] = dist[fr] + ed[y].we;
          par[ed[y].to] = fr;
          eu[ed[y].to] = y;
          if (!vis[ed[y].to]) {
            qu.push(ed[y].to), vis[ed[y].to] = true;
          }
        }
      }
    }
    ans += dist[t];
    int node = t;
    while (node != s) {
      ed[eu[node]].flow++;
      ed[eu[node] ^ 1].flow--;
      node = par[node];
    }
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> q;
  fill(ub, ub + n, n - 1);
  fill(lb, lb + n, 0);
  for (int i = (0); i < (q); ++i) {
    int t, l, r, v;
    cin >> t >> l >> r >> v;
    l--, v--;
    if (t == 1) {
      for (int j = (l); j < (r); ++j) {
        lb[j] = max(lb[j], v);
      }
    } else {
      for (int j = (l); j < (r); ++j) {
        ub[j] = min(ub[j], v);
      }
    }
  }
  for (int i = (0); i < (n); ++i) {
    if (lb[i] > ub[i]) {
      cout << -1 << endl;
      return 0;
    }
  }
  s = 2 * n;
  t = s + 1;
  for (int i = 0; i < n; ++i) {
    add_edge(s, i, 1, 0);
    for (int j = lb[i]; j <= ub[i]; ++j) add_edge(i, n + j, 1, 0);
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) add_edge(i + n, t, 1, j * 2 + 1);
  }
  cout << flow() << "\n";
  return 0;
}
