#include <bits/stdc++.h>
using namespace std;
int n, q;
namespace flow {
const int MAXM = 1.2e7 + 6;
int N;
int head[200036], to[MAXM], nex[MAXM], wto[MAXM], cto[MAXM], cur[200036],
    ecn = -1;
inline void Ade(int u, int v, int w, int c) {
  to[++ecn] = v, nex[ecn] = head[u], wto[ecn] = w, cto[ecn] = c, head[u] = ecn;
}
inline void ade(int u, int v, int w, int c) {
  Ade(u, v, w, c), Ade(v, u, 0, -c);
}
void in(int t) {
  N = t;
  for (int i = (1), iend = (N); i <= iend; ++i) head[i] = -1;
  ecn = -1;
}
queue<int> Q;
int dis[200036], vis[200036];
const int inf = 1e9;
int s, t;
bool spfa() {
  memset(dis, 0x3f, sizeof dis), memset(vis, 0, sizeof vis);
  for (int i = (1), iend = (N); i <= iend; ++i) cur[i] = head[i];
  dis[s] = 0, vis[s] = 1;
  Q.push(s);
  while (!Q.empty()) {
    int u = Q.front();
    Q.pop();
    vis[u] = 0;
    for (int i = head[u]; ~i; i = nex[i])
      if (wto[i] && dis[to[i]] > dis[u] + cto[i]) {
        int v = to[i];
        dis[v] = dis[u] + cto[i];
        if (!vis[v]) Q.push(v), vis[v] = 1;
      }
  }
  return dis[t] < inf;
}
int co;
int dfs(int u, int lim) {
  if (!lim || u == t) return lim;
  vis[u] = 1;
  int f, flow = 0;
  for (int& i = cur[u]; ~i; i = nex[i])
    if (!vis[to[i]] && wto[i] && dis[to[i]] == dis[u] + cto[i] &&
        (f = dfs(to[i], min(lim, wto[i])))) {
      lim -= f, flow += f, wto[i] -= f, wto[i ^ 1] += f;
      co += f * cto[i];
      if (!lim) break;
    }
  vis[u] = 0;
  return flow;
}
pair<int, int> dinic() {
  int re = 0;
  co = 0;
  while (spfa()) {
    re += dfs(s, 0x3f3f3f3f);
  }
  return make_pair(re, co);
}
}  // namespace flow
int mn[200036], mx[200036];
void solve() {
  cin >> n >> q;
  for (int i = (1), iend = (n); i <= iend; ++i) mn[i] = 1, mx[i] = n;
  for (int i = (1), iend = (q); i <= iend; ++i) {
    int t, l, r, v;
    scanf("%d%d%d%d", &t, &l, &r, &v);
    if (t == 1)
      for (int j = (l), jend = (r); j <= jend; ++j) mn[j] = max(mn[j], v);
    else
      for (int j = (l), jend = (r); j <= jend; ++j) mx[j] = min(mx[j], v);
  }
  flow::in(n * n + n + 6);
  flow::s = n * n + n + 1, flow::t = n * n + n + 2;
  int s = flow::s, t = flow::t;
  for (int i = (1), iend = (n); i <= iend; ++i) {
    for (int j = (mn[i]), jend = (mx[i]); j <= jend; ++j) {
      int cur = j + i * n;
      if (j == mn[i]) flow::ade(s, cur, 1, 0);
      if (j != mx[i]) flow::ade(cur, cur + 1, 1, 0);
      flow::ade(cur, j, 1, 0);
    }
  }
  for (int i = (1), iend = (n); i <= iend; ++i)
    for (int j = (1), jend = (n); j <= jend; ++j) flow::ade(i, t, 1, 2 * j - 1);
  pair<int, int> fl = flow::dinic();
  if (fl.first != n)
    puts("-1");
  else
    cout << fl.second << endl;
}
signed main() { solve(); }
