1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <vector>
#include <map>
#include <unordered_set>
#include <queue>
#include <unordered_map>
#include <math.h>
#include <limits.h>
#include <algorithm>
#include <functional>
#include <iterator>
#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

#define pb push_back
#define mp make_pair

typedef long long ll;
typedef unsigned long long ull;

using namespace std;

int YELLOW = 1;
int BLUE = 2;
int RED = 3;

int opened[4];

struct X {
  int point;
  int color;
  bool open;
};

bool compareX(X& x1, X& x2) {
  return x1.point < x2.point || (x1.point == x2.point && x1.open);
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);

  vector<X> v;

  int n, m;
  cin >> n >> m;
  int l, r, c;
  for (int i=0; i<m; ++i) {
    cin >> l >> r >> c;
    v.pb({l, c, true});
    v.pb({r, c, false});
  }

  std::sort(v.begin(), v.end(), compareX);

  int prev = 1;
  bool green = false;
  int answer = 0;
  bool red_opened = false;
  bool pot_green = false;
  for (int i=0; i<v.size(); ++i) {
    auto p = v[i];
    if (p.open) {
      opened[p.color] += 1;
    } else {
      opened[p.color] -= 1;
    }
    red_opened = red_opened || (p.color == RED);
    pot_green = pot_green || (opened[YELLOW] && opened[BLUE]);
    if (i < v.size()-1 && v[i].point == v[i+1].point) continue;

    bool now_green = opened[YELLOW] && opened[BLUE] && !opened[RED];

    if (green) {
      answer += p.point - prev;
    } 
    if (!red_opened && pot_green) {
      answer += 1;
    }

    green = now_green;
    prev = p.point + 1;
    red_opened = opened[RED];
    pot_green = green;
  }

  cout << answer << endl;

  return 0;
}