#include <bits/stdc++.h>
using namespace std;
const int INF = 0x7f7f7f7f;
int n, m, s, t, u[10005], d[10005];
int mxf, mnc;
int ee = 1, h[5005], nex[50005 << 1], to[50005 << 1], val[50005 << 1],
    cost[50005 << 1];
int dis[5005], pre[5005], last[5005], flow[5005];
bool vis[5005];
void addedge(int x, int y, int z, int c) {
  nex[++ee] = h[x];
  to[ee] = y;
  val[ee] = z;
  cost[ee] = c;
  h[x] = ee;
}
bool spfa() {
  memset(dis, INF, sizeof(dis));
  memset(flow, INF, sizeof(flow));
  memset(vis, false, sizeof(vis));
  queue<int> q;
  q.push(s);
  vis[s] = true;
  dis[s] = 0;
  pre[t] = -1;
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    vis[x] = false;
    for (int i = h[x]; i; i = nex[i])
      if (val[i] && dis[to[i]] > dis[x] + cost[i]) {
        dis[to[i]] = dis[x] + cost[i];
        pre[to[i]] = x;
        last[to[i]] = i;
        flow[to[i]] = min(flow[x], val[i]);
        if (!vis[to[i]]) {
          vis[to[i]] = true;
          q.push(to[i]);
        }
      }
  }
  return pre[t] != -1;
}
void mcmf() {
  while (spfa()) {
    int now = t;
    mxf += flow[t];
    mnc += flow[t] * dis[t];
    while (now != s) {
      val[last[now]] -= flow[t];
      val[last[now] ^ 1] += flow[t];
      now = pre[now];
    }
  }
}
int main() {
  cin >> n >> m;
  s = 0, t = 2 * n + 1;
  for (int i = 1; i <= n; i++) u[i] = 1, d[i] = n;
  for (int i = 1; i <= n; i++) addedge(s, i, 1, 0), addedge(i, s, 0, 0);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
      addedge(i + n, t, 1, j * j - (j - 1) * (j - 1)),
          addedge(t, i + n, 0, -(j * j - (j - 1) * (j - 1)));
  for (int i = 1, oper, l, r, v; i <= m && scanf("%d%d%d%d", &oper, &l, &r, &v);
       i++)
    for (int j = l; j <= r; j++)
      if (oper == 1)
        u[j] = max(u[j], v);
      else if (oper == 2)
        d[j] = min(d[j], v);
  for (int i = 1; i <= n; i++)
    for (int j = u[i]; j <= d[i]; j++)
      addedge(i, j + n, 1, 0), addedge(j + n, i, 0, 0);
  mcmf();
  cout << (mxf < n ? -1 : mnc) << endl;
  return 0;
}
