#include <bits/stdc++.h>
using namespace std;
using INT = long long;
using pii = pair<int, int>;
struct edge {
  int to, capacity, cost, rev;
  edge() {}
  edge(int to, int _capacity, int _cost, int _rev)
      : to(to), capacity(_capacity), cost(_cost), rev(_rev) {}
};
const int inf = 0x3f3f3f3f;
struct Min_Cost_Max_Flow {
  int V, H[10100 + 5], dis[10100 + 5], PreV[10100 + 5], PreE[10100 + 5];
  vector<edge> G[10100 + 5];
  void Init(int n) {
    V = n;
    for (int i = 0; i <= V; ++i) G[i].clear();
  }
  void add_edge(int from, int to, int cap, int cost) {
    G[from].push_back(edge(to, cap, cost, G[to].size()));
    G[to].push_back(edge(from, 0, -cost, G[from].size() - 1));
  }
  int minCost(int s, int t, int f) {
    int flow = 0;
    int res = 0;
    fill(H, H + 1 + V, 0);
    while (f) {
      priority_queue<pii, vector<pii>, greater<pii> > q;
      fill(dis, dis + 1 + V, inf);
      dis[s] = 0;
      q.push(pii(0, s));
      while (!q.empty()) {
        pii now = q.top();
        q.pop();
        int v = now.second;
        if (dis[v] < now.first) continue;
        for (int i = 0; i < G[v].size(); ++i) {
          edge& e = G[v][i];
          if (e.capacity > 0 && dis[e.to] > dis[v] + e.cost + H[v] - H[e.to]) {
            dis[e.to] = dis[v] + e.cost + H[v] - H[e.to];
            PreV[e.to] = v;
            PreE[e.to] = i;
            q.push(pii(dis[e.to], e.to));
          }
        }
      }
      if (dis[t] == inf) break;
      for (int i = 0; i <= V; ++i) H[i] += dis[i];
      int d = f;
      for (int v = t; v != s; v = PreV[v])
        d = min(d, G[PreV[v]][PreE[v]].capacity);
      f -= d;
      flow += d;
      res += d * H[t];
      for (int v = t; v != s; v = PreV[v]) {
        edge& e = G[PreV[v]][PreE[v]];
        e.capacity -= d;
        G[v][e.rev].capacity += d;
      }
    }
    return res;
  }
} mcmf;
int n, q;
int t[10100], l[10100], r[10100], v[10100];
int mn[10100], mx[10100];
int main() {
  cin >> n >> q;
  for (int i = 1; i <= n; i++) {
    mn[i] = 1;
    mx[i] = n;
  }
  for (int i = 1; i <= q; i++) {
    scanf("%d %d %d %d", t + i, l + i, r + i, v + i);
    if (t[i] == 1) {
      for (int j = l[i]; j <= r[i]; j++) {
        mn[j] = max(mn[j], v[i]);
      }
    } else {
      for (int j = l[i]; j <= r[i]; j++) {
        mx[j] = min(mx[j], v[i]);
      }
    }
  }
  for (int i = 1; i <= n; i++)
    if (mn[i] > mx[i]) return puts("-1"), 0;
  int src = n * 2 + 1, tar = src + 1;
  mcmf.Init(tar + 10);
  for (int i = 1; i <= n; i++) {
    mcmf.add_edge(src, i, 1, 0);
    for (int j = mn[i]; j <= mx[i]; j++) {
      mcmf.add_edge(i, j + n, 1, 0);
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      mcmf.add_edge(n + i, tar, 1, j * 2 - 1);
    }
  }
  cout << mcmf.minCost(src, tar, n) << endl;
}
