#include <bits/stdc++.h>
using namespace std;
const int maxn = 505;
int l[maxn], r[maxn];
struct Edge {
  int to, next;
  long long val, cost;
} edge[100010];
int head[maxn], cnt = 0;
void add(int u, int v, long long val, long long cost) {
  edge[cnt].to = v;
  edge[cnt].val = val;
  edge[cnt].cost = cost;
  edge[cnt].next = head[u];
  head[u] = cnt++;
}
int s, e, tot;
int exist[maxn], preid[maxn], tag[100010];
long long dist[maxn];
bool spfa() {
  for (int i = 0; i <= tot; i++) {
    dist[i] = 1e18;
  }
  memset(preid, 0, sizeof(preid));
  memset(tag, 0, sizeof(tag));
  memset(exist, 0, sizeof(exist));
  queue<int> q;
  q.push(s);
  exist[s] = 1;
  dist[s] = 0;
  while (!q.empty()) {
    int x = q.front();
    exist[x] = 0;
    q.pop();
    for (int i = head[x]; i != -1; i = edge[i].next) {
      Edge t = edge[i];
      if (t.val && dist[t.to] > dist[x] + t.cost) {
        dist[t.to] = dist[x] + t.cost;
        preid[t.to] = x;
        tag[t.to] = i;
        if (!exist[t.to]) {
          q.push(t.to);
          exist[t.to] = 1;
        }
      }
    }
  }
  if (dist[e] == 1e18) return false;
  return true;
}
void mcmf(long long &flow, long long &cost) {
  while (spfa()) {
    long long mi = 1e18;
    for (int t = e; t != s; t = preid[t]) {
      mi = min(mi, edge[tag[t]].val);
    }
    for (int t = e; t != s; t = preid[t]) {
      edge[tag[t]].val -= mi;
      edge[tag[t] ^ 1].val += mi;
    }
    flow += mi;
    cost += (long long)mi * dist[e];
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  memset(head, -1, sizeof(head));
  int n, q;
  cin >> n >> q;
  for (int i = 1; i <= n; i++) l[i] = 1, r[i] = n;
  for (int i = 1; i <= q; i++) {
    int k, lx, rx, v;
    cin >> k >> lx >> rx >> v;
    for (int j = lx; j <= rx; j++) {
      if (k == 1)
        l[j] = max(l[j], v);
      else
        r[j] = min(r[j], v);
    }
  }
  s = 0, e = 2 * n + 1, tot = e;
  for (int i = 1; i <= n; i++) {
    add(s, i, 1, 0), add(i, s, 0, 0);
    for (int j = l[i]; j <= r[i]; j++) {
      add(i, j + n, 1, 0), add(j + n, i, 0, 0);
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      add(i + n, e, 1, 2 * j - 1), add(e, i + n, 0, 1 - 2 * j);
    }
  }
  long long flow = 0, cost = 0;
  mcmf(flow, cost);
  if (flow != n)
    cout << -1 << '\n';
  else
    cout << cost << '\n';
  return 0;
}
