#include <bits/stdc++.h>
using namespace std;
int tp, te, start, en, sp, ans, ac, dist[205], u[205], d[205];
bool vis[205], vd[205];
vector<int> edge[205], stream[205], cost[205], size[205];
void add(int f, int t, int nowstream, int nowcost) {
  edge[f].push_back(t);
  edge[t].push_back(f);
  stream[f].push_back(nowstream);
  stream[t].push_back(0);
  cost[f].push_back(nowcost);
  cost[t].push_back(-nowcost);
  size[f].push_back(edge[t].size() - 1);
  size[t].push_back(edge[f].size() - 1);
}
bool spfa(int start, int en) {
  queue<int> q;
  int i, nxt, top;
  for (i = 1; i <= sp; i++) {
    vd[i] = false;
    vis[i] = false;
    dist[i] = 2147483647;
  }
  vis[start] = true;
  dist[start] = 0;
  q.push(start);
  while (!q.empty()) {
    top = q.front();
    q.pop();
    vis[top] = false;
    for (i = 0; i < edge[top].size(); i++) {
      nxt = edge[top][i];
      if (dist[top] + cost[top][i] < dist[nxt] && stream[top][i]) {
        dist[nxt] = dist[top] + cost[top][i];
        if (!vis[nxt]) {
          vis[nxt] = true;
          q.push(nxt);
        }
      }
    }
  }
  return dist[en] != 2147483647;
}
int dfs(int now, int en, int mi) {
  if (!mi || now == en) return mi;
  int i, rtn, nxt, mr;
  rtn = 0;
  vd[now] = 1;
  for (i = 0; i < edge[now].size(); i++) {
    nxt = edge[now][i];
    if (dist[now] + cost[now][i] == dist[nxt] && stream[now][i] && !vd[nxt]) {
      mr = dfs(nxt, en, min(mi, stream[now][i]));
      stream[now][i] -= mr;
      stream[nxt][size[now][i]] += mr;
      mi -= mr;
      rtn += mr;
      ac += mr * cost[now][i];
    }
  }
  return rtn;
}
void mm() {
  while (spfa(start, en)) {
    ans = ans + dfs(start, en, 2147483647);
  }
}
int main() {
  int i, j, l, r, opt, val;
  cin >> tp >> te;
  start = tp * 2 + 1;
  en = tp * 2 + 2;
  sp = tp * 2 + 2;
  for (i = 1; i <= tp; i++) {
    u[i] = 1;
    d[i] = tp;
  }
  for (i = 1; i <= te; i++) {
    cin >> opt >> l >> r >> val;
    for (j = l; j <= r; j++) {
      if (opt == 1) {
        u[j] = max(u[j], val);
      } else {
        d[j] = min(d[j], val);
      }
    }
  }
  for (i = 1; i <= tp; i++) {
    add(start, i, 1, 0);
  }
  for (i = 1; i <= tp; i++) {
    for (j = u[i]; j <= d[i]; j++) {
      add(i, j + tp, 1, 0);
    }
  }
  for (i = 1; i <= tp; i++) {
    for (j = 1; j <= tp; j++) {
      add(i + tp, en, 1, 2 * j - 1);
    }
  }
  mm();
  if (ans == tp) {
    cout << ac << endl;
  } else
    puts("-1");
  return 0;
}
