#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 2277;
const int N = 155;
int n, s, t, low[N], high[N], q;
class Flows {
 public:
  struct edge {
    int u, v, cap, cost, flow;
    edge(int u = 0, int v = 0, int cap = 0, int flow = 0, int cost = 0) {
      this->u = u;
      this->v = v;
      this->cap = cap;
      this->flow = flow;
      this->cost = cost;
    }
  };
  vector<edge> e;
  vector<int> g[N];
  int dist[N], par[N];
  bool inqueue[N];
  queue<int> q;
  bool FordBellman() {
    while (!q.empty()) q.pop();
    for (int i = 0; i < N; i++) dist[i] = inf;
    for (int i = 0; i < N; i++) par[i] = 0;
    for (int i = 0; i < N; i++) inqueue[i] = false;
    q.push(s);
    dist[s] = 0;
    par[s] = inf;
    inqueue[s] = true;
    while (!q.empty()) {
      int u = q.front();
      q.pop();
      inqueue[u] = false;
      for (int i = 0; i < g[u].size(); i++) {
        int V = g[u][i];
        edge ed = e[V];
        int v = (ed.u == u ? ed.v : ed.u);
        if (dist[v] > dist[u] + ed.cost && ed.flow < ed.cap) {
          dist[v] = dist[u] + ed.cost;
          par[v] = V;
          if (!inqueue[v]) {
            q.push(v);
            inqueue[v] = true;
          }
        }
      }
    }
    return par[t] != 0;
  }
  int edmond_karp() {
    int u = t;
    int cur_flow = inf;
    while (u != s) {
      cur_flow = min(cur_flow, e[par[u]].cap - e[par[u]].flow);
      u = (e[par[u]].u == u ? e[par[u]].v : e[par[u]].u);
    }
    u = t;
    while (u != s) {
      e[par[u]].flow += cur_flow;
      e[par[u] ^ 1].flow -= cur_flow;
      u = (e[par[u]].u == u ? e[par[u]].v : e[par[u]].u);
    }
    return cur_flow;
  }
  void addEdge(int u, int v, int cap, int cost) {
    g[u].push_back(e.size());
    g[v].push_back(e.size() + 1);
    e.push_back(edge(u, v, cap, 0, cost));
    e.push_back(edge(v, u, 0, 0, -cost));
  }
  pair<int, int> solve() {
    int mincost = 0;
    int maxflow = 0;
    while (FordBellman()) maxflow += edmond_karp();
    for (int i = 0; i < e.size(); i++)
      if (e[i].flow) mincost = mincost + e[i].flow * e[i].cost;
    return make_pair(mincost, maxflow);
  }
} mcmf;
int main() {
  scanf("%d %d", &n, &q);
  for (int i = 0; i < N; i++) {
    low[i] = 0;
    high[i] = inf;
  }
  while (q--) {
    int type, l, r, v;
    scanf("%d %d %d %d", &type, &l, &r, &v);
    if (type == 1)
      for (int i = l; i <= r; i++) low[i] = max(low[i], v);
    else
      for (int i = l; i <= r; i++) high[i] = min(high[i], v);
  }
  s = 0;
  t = 2 * n + 1;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= 2 * n - 1; j = j + 2) mcmf.addEdge(s, i, 1, j);
  for (int i = n + 1; i <= 2 * n; i++) mcmf.addEdge(i, t, 1, 0);
  for (int i = 1; i <= n; i++)
    for (int j = n + 1; j <= 2 * n; j++)
      if (i >= low[j - n] && i <= high[j - n]) mcmf.addEdge(i, j, 1, 0);
  pair<int, int> ans = mcmf.solve();
  if (ans.second != n)
    printf("%d", -1);
  else
    printf("%d", ans.first / 2);
  return 0;
}
