#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
const int NN = 222;
const int MM = 222222;
const int inf = 0x3f3f3f3f;
int dis[NN], src, tar;
int E, head[NN], to[MM], nxt[MM], flow[MM], cost[MM], pre[NN];
int C;
pii p[NN];
void add_edge(int u, int v, int f, int c) {
  nxt[E] = head[u];
  to[E] = v;
  flow[E] = f;
  cost[E] = c;
  head[u] = E++;
  nxt[E] = head[v];
  to[E] = u;
  flow[E] = 0;
  cost[E] = -c;
  head[v] = E++;
}
queue<int> q;
pii maxflow(int s, int t) {
  int ans = 0, u, v, bot;
  while (1) {
    q = queue<int>();
    q.push(s);
    memset(dis, inf, sizeof(dis));
    dis[s] = 0;
    while (!q.empty()) {
      u = q.front();
      q.pop();
      for (int e = head[u]; ~e; e = nxt[e]) {
        v = to[e];
        if (flow[e] == 0) continue;
        if (dis[v] > dis[u] + cost[e]) {
          dis[v] = dis[u] + cost[e];
          q.push(v);
          pre[v] = e;
        }
      }
    }
    if (dis[t] == inf) return {ans, C};
    bot = inf;
    for (u = t; u != s; u = to[pre[u] ^ 1]) bot = min(bot, flow[pre[u]]);
    for (u = t; u != s; u = to[pre[u] ^ 1]) {
      flow[pre[u]] -= bot;
      flow[pre[u] ^ 1] += bot;
    }
    C += dis[t];
    ans += bot;
  }
}
int main() {
  int n, q;
  scanf("%d %d", &n, &q);
  for (int i = 1; i <= n; i++) {
    p[i].first = 1;
    p[i].second = n;
  }
  memset(head, -1, sizeof head);
  int t, l, r, first;
  for (int i = 1; i <= q; i++) {
    scanf("%d %d %d %d", &t, &l, &r, &first);
    if (t == 1) {
      for (int j = l; j <= r; j++) {
        p[j].first = max(p[j].first, first);
        if (p[j].first > p[j].second) {
          puts("-1");
          return 0;
        }
      }
    } else {
      for (int j = l; j <= r; j++) {
        p[j].second = min(p[j].second, first);
        if (p[j].first > p[j].second) {
          puts("-1");
          return 0;
        }
      }
    }
  }
  src = 0;
  tar = 2 * n + 1;
  for (int i = 1; i <= n; i++) {
    add_edge(src, i, 1, 0);
  }
  for (int i = 1; i <= n; i++) {
    for (int j = p[i].first; j <= p[i].second; j++) add_edge(i, n + j, 1, 0);
    for (int j = 0; j <= n; j++) {
      add_edge(n + i, tar, 1, 2 * j + 1);
    }
  }
  if (maxflow(src, tar).first != n) {
    puts("-1");
    return 0;
  }
  cout << C << endl;
  return 0;
}
