#include <bits/stdc++.h>
std::vector<int> a[105], b[105], c[105], f[105];
int n, m, s, t, sp, flow = 0, cost = 0, dis[105], vis[105], use[105], u[55],
                    d[55];
std::queue<int> q;
void add(int x, int y, int v, int w) {
  a[x].push_back(y);
  a[y].push_back(x);
  b[x].push_back(v);
  b[y].push_back(0);
  c[x].push_back(w);
  c[y].push_back(-w);
  f[x].push_back(a[y].size() - 1), f[y].push_back(a[x].size() - 1);
}
int spfa(int s, int t) {
  for (int i = 1; i <= sp; i++) dis[i] = 1000000000, vis[i] = 0, use[i] = 0;
  dis[s] = 0;
  vis[s] = 1;
  q.push(s);
  while (!q.empty()) {
    int v = q.front();
    q.pop();
    vis[v] = 0;
    for (int i = 0; i < a[v].size(); i++) {
      int u = a[v][i];
      if (dis[v] + c[v][i] < dis[u] && b[v][i]) {
        dis[u] = dis[v] + c[v][i];
        if (!vis[u]) q.push(u), vis[u] = 1;
      }
    }
  }
  return dis[t] != 1000000000;
}
int dfs(int v, int t, int now) {
  if (v == t || !now) return now;
  int fl = 0;
  use[v] = 1;
  for (int i = 0; i < a[v].size(); i++) {
    int u = a[v][i];
    if (dis[v] + c[v][i] == dis[u] && b[v][i] && !use[u]) {
      int k = dfs(u, t, std::min(b[v][i], now));
      b[v][i] = b[v][i] - k;
      b[u][f[v][i]] = b[u][f[v][i]] + k;
      fl = fl + k;
      now = now - k;
      cost = cost + k * c[v][i];
    }
  }
  return fl;
}
void mcmf() {
  while (spfa(s, t)) flow = flow + dfs(s, t, 1000000000);
}
int main() {
  scanf("%d%d", &n, &m);
  s = n * 2 + 1, t = 2 * n + 2, sp = 2 * n + 2;
  for (int i = 1; i <= n; i++) u[i] = 1, d[i] = n;
  for (int i = 1; i <= m; i++) {
    int opt, l, r, v;
    scanf("%d%d%d%d", &opt, &l, &r, &v);
    for (int i = l; i <= r; i++)
      opt == 1 ? u[i] = std::max(u[i], v) : d[i] = std::min(d[i], v);
  }
  for (int i = 1; i <= n; i++) add(s, i, 1, 0);
  for (int i = 1; i <= n; i++)
    for (int j = u[i]; j <= d[i]; j++) add(i, j + n, 1, 0);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++) add(i + n, t, 1, 2 * j - 1);
  mcmf();
  if (flow == n)
    printf("%d\n", cost);
  else
    puts("-1");
  return 0;
}
