#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
struct MCF {
  int n;
  vector<long long> prio, curflow, prevedge, prevnode, pot;
  priority_queue<long long, vector<long long>, greater<long long>> q;
  struct edge {
    int to, rev;
    long long f, cap, cost;
  };
  vector<vector<edge>> g;
  MCF(int n)
      : n(n), prio(n), curflow(n), prevedge(n), prevnode(n), pot(n), g(n) {}
  void add_edge(int s, int t, long long cap, long long cost) {
    g[s].push_back((edge){t, int((g[t]).size()), 0, cap, cost});
    g[t].push_back((edge){s, int((g[s]).size()) - 1, 0, 0, -cost});
  }
  pair<long long, long long> get_flow(int s, int t) {
    long long flow = 0, flowcost = 0;
    while (1) {
      q.push(s);
      fill((prio).begin(), (prio).end(), INF);
      prio[s] = 0;
      curflow[s] = INF;
      while (!q.empty()) {
        long long cur = q.top();
        int d = cur >> 32, u = cur;
        q.pop();
        if (d != prio[u]) continue;
        for (int i = 0; i < int((g[u]).size()); ++i) {
          edge &e = g[u][i];
          int v = e.to;
          if (e.cap <= e.f) continue;
          long long nprio = prio[u] + e.cost + pot[u] - pot[v];
          if (prio[v] > nprio) {
            prio[v] = nprio;
            q.push(((long long)nprio << 32) + v);
            prevnode[v] = u;
            prevedge[v] = i;
            curflow[v] = min(curflow[u], e.cap - e.f);
          }
        }
      }
      if (prio[t] == INF) break;
      for (int i = int(0); i < int(n); ++i) pot[i] += prio[i];
      long long df = min(curflow[t], INF - flow);
      flow += df;
      for (int v = t; v != s; v = prevnode[v]) {
        edge &e = g[prevnode[v]][prevedge[v]];
        e.f += df;
        g[v][e.rev].f -= df;
        flowcost += df * e.cost;
      }
    }
    return {flow, flowcost};
  }
};
const int N = 100;
int lo[N], hi[N];
int main() {
  int n, q;
  scanf("%d%d", &n, &q);
  for (int i = int(0); i < int(n); ++i) lo[i] = 0, hi[i] = n;
  while (q--) {
    int ty, l, r, val;
    scanf("%d%d%d%d", &ty, &l, &r, &val);
    l--;
    val--;
    if (ty == 1)
      for (int i = int(l); i < int(r); ++i) lo[i] = max(lo[i], val);
    else
      for (int i = int(l); i < int(r); ++i) hi[i] = min(hi[i], val + 1);
  }
  for (int i = int(0); i < int(n); ++i) {
    if (lo[i] >= hi[i]) {
      cout << -1 << endl;
      return 0;
    }
  }
  MCF mcf(n * n + n + 5);
  for (int i = int(0); i < int(n); ++i)
    for (int j = int(lo[i]); j < int(hi[i]); ++j)
      for (int k = int(0); k < int(n); ++k)
        mcf.add_edge(i + n * n, j * n + k, 1, 2 * k + 1);
  for (int i = int(0); i < int(n); ++i)
    mcf.add_edge(n * n + n + 1, i + n * n, 1, 0);
  for (int i = int(0); i < int(n * n); ++i)
    mcf.add_edge(i, n * n + n + 2, 1, 0);
  pair<int, int> x = mcf.get_flow(n * n + n + 1, n * n + n + 2);
  cout << x.second << endl;
  return 0;
}
