#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 5;
long long mod = 1e9 + 7;
const int lim = 5e5;
const int lg = 20;
const int base = 311;
const long double eps = 1e-6;
struct Edge {
  long long flow, cap, from, to, cost;
  Edge(long long f, long long c, long long fr, long long t, long long co) {
    flow = f, cap = c, from = fr, to = t, cost = co;
  }
};
vector<Edge> E;
vector<long long> adj[N];
void AddEgde(long long u, long long v, long long cap, long long cost) {
  adj[u].push_back(E.size());
  E.push_back(Edge(0ll, cap, u, v, cost));
  adj[v].push_back(E.size());
  E.push_back(Edge(0ll, 0ll, v, u, -cost));
}
long long totFlow = 0, tot;
long long p[N], dp[N], mn[N], mx[N];
long long dfs(long long s, long long t) {
  for (int i = 1; i <= tot; i++) dp[i] = 1e18, p[i] = -1;
  priority_queue<pair<long long, long long>, vector<pair<long long, long long>>,
                 greater<pair<long long, long long>>>
      pq;
  pq.push({0, s});
  dp[s] = 0;
  while (pq.size()) {
    pair<long long, long long> x = pq.top();
    pq.pop();
    if (dp[x.second] != x.first) continue;
    for (auto j : adj[x.second]) {
      if (E[j].cap > E[j].flow) {
        long long v = E[j].to, c = E[j].cost;
        if (dp[v] > (x.first + c)) {
          p[v] = j;
          dp[v] = x.first + c;
          pq.push({dp[v], v});
        }
      }
    }
  }
  return dp[t] < 1e18;
}
long long MaxFlow(long long s, long long t) {
  long long mnCost = 0;
  long long cost;
  while (cost = dfs(s, t)) {
    long long now = t;
    while (true) {
      long long last = p[now];
      long long newt = E[last].from;
      E[last].flow++;
      E[last ^ 1].flow--;
      mnCost += E[last].cost;
      if (newt == s) break;
      now = newt;
    }
    totFlow++;
  }
  return mnCost;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  if (fopen("A.inp", "r")) {
    freopen("test.inp", "r", stdin);
    freopen("test.out", "w", stdout);
  }
  long long n, q;
  cin >> n >> q;
  for (int i = 1; i <= n; i++) mn[i] = 1, mx[i] = n;
  while (q--) {
    long long task, l, r, v;
    cin >> task >> l >> r >> v;
    if (task == 1) {
      for (int i = l; i <= r; i++) {
        mn[i] = max(mn[i], v);
      }
    } else {
      for (int i = l; i <= r; i++) {
        mx[i] = min(mx[i], v);
      }
    }
  }
  tot = n + n;
  tot++;
  long long s = tot;
  tot++;
  long long t = tot;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      AddEgde(s, i, 1, 2 * j - 1);
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = mn[i]; j <= mx[i]; j++) {
      AddEgde(j, i + n, 1, 0);
    }
  }
  for (int i = 1; i <= n; i++) {
    AddEgde(i + n, t, 1, 0);
  }
  long long res = MaxFlow(s, t);
  if (totFlow != n)
    cout << -1;
  else
    cout << res;
}
