#include <bits/stdc++.h>
using namespace std;
int n, q;
unordered_map<int, pair<int, int>> resi[50 * 3 + 2];
struct FLOW {
  int n, *pre, *dist;
  FLOW(int n) : n(n) {
    pre = (int *)malloc((n + 2) * sizeof(int));
    dist = (int *)malloc((n + 2) * sizeof(int));
  }
  ~FLOW() {
    free(pre);
    free(dist);
  }
  pair<int, int> SAP() {
    int flow = 0, cost = 0;
    for (; SPFA();) {
      for (int i = n + 1; i != n; i = pre[i]) {
        assert(resi[pre[i]].count(i));
        resi[pre[i]][i].first -= pre[n];
        if (resi[i].count(pre[i]))
          resi[i][pre[i]].first += pre[n];
        else
          resi[i][pre[i]] = make_pair(pre[n], -resi[pre[i]][i].second);
      }
      flow += pre[n];
      cost += pre[n] * dist[n + 1];
    }
    return make_pair(flow, cost);
  }
  bool SPFA() {
    int nn = n + 2, q[nn + 1];
    bool v[nn];
    int h = 0, l = 1, x;
    for (int i = 0; i < nn; i++) dist[i] = (50 * 50 * 50);
    memset(pre, -1, nn * sizeof(int));
    memset(v, false, nn * sizeof(bool));
    dist[n] = 0, pre[n] = -1;
    q[0] = n, v[n] = true;
    while (l != 0) {
      x = q[h];
      v[q[h]] = false;
      l--;
      h = (h + 1) % nn;
      for (unordered_map<int, pair<int, int>>::const_iterator ix =
               resi[x].begin();
           ix != resi[x].end(); ix++) {
        if (ix->second.first == 0) continue;
        int i = ix->first, p = ix->second.second;
        if (dist[x] + p < dist[i]) {
          dist[i] = dist[x] + p;
          pre[i] = x;
          if (!v[i]) v[q[(h + l++) % nn] = i] = true;
        }
      }
    }
    if (pre[n + 1] != -1) {
      int flow = (50 * 50 * 50);
      for (int i = n + 1; i != n; i = pre[i])
        if (resi[pre[i]][i].first < flow) flow = resi[pre[i]][i].first;
      pre[n] = flow;
    }
    return pre[n + 1] != -1;
  }
};
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> q;
  int arr[n][2], t, l, r, v;
  for (int i = 0; i < n; i++) arr[i][0] = 1, arr[i][1] = n;
  for (int iq = 0; iq < q; iq++) {
    cin >> t >> l >> r >> v;
    if (t == 1)
      for (int i = l - 1; i < r; i++) arr[i][0] = max(arr[i][0], v);
    else if (t == 2)
      for (int i = l - 1; i < r; i++) arr[i][1] = min(arr[i][1], v);
  }
  for (int i = 0; i < n; i++) {
    resi[3 * n][i] = make_pair(1, 0);
    resi[2 * n + i][3 * n + 1] = make_pair(n, 2 * i + 1);
    for (int j = 0; j < n; j++) resi[n + i][2 * n + j] = make_pair(1, 0);
    for (int j = arr[i][0] - 1; j < arr[i][1]; j++)
      resi[i][n + j] = make_pair(1, 0);
  }
  FLOW flow(3 * n);
  pair<int, int> ans = flow.SAP();
  if (ans.first != n)
    cout << -1 << endl;
  else
    cout << ans.second << endl;
  return 0;
}
