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
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;

vector<pair<int,int>> op, cz, cn, cc, czc, cnc, ccc;
int n, o, l, r, k;
long long int ans = 0;

void joint(vector<pair<int,int>> &arr1, vector<pair<int,int>> &arr2) 
{ 
    int i = 0, j = 0; 
    while (i < arr1.size() && j < arr2.size()) { 
        l = max(arr1[i].first, arr2[j].first); 
        r = min(arr1[i].second, arr2[j].second); 
        if (l <= r) {
            if(arr1 != op) {
                ans += r - l + 1;
                op.push_back(make_pair(l,r));
            }
            else 
                ans -= r - l + 1;
        }       
        (arr1[i].second < arr2[j].second) ? i++ : j++;
    } 
} 

vector<pair<int,int>> merge(vector<pair<int,int>>& v) 
{
    sort(v.begin(), v.end());
    vector<pair<int,int>> stack;
    if (v.empty())
        return stack;
    stack.push_back(v[0]);
    for (int i = 1; i < v.size(); i++) {
        pair<int,int> top = stack.back();
        if (top.second < v[i].first)
            stack.push_back(v[i]);
        else if (top.second < v[i].second) {
            top.second = v[i].second;
            stack.pop_back();
            stack.push_back(top);
        }
    }
    return stack;    
}


int main()
{
    ios_base::sync_with_stdio(false);
    cin >> n >> o;
    for (int i=0; o > i; i++) {
        cin >> l >> r >> k;
        (k == 1) ? cz.push_back(make_pair(l,r)) : (k == 2) ? cn.push_back(make_pair(l,r)) : cc.push_back(make_pair(l,r));   
    }

    czc = merge(cz);
    cnc = merge(cn);
    ccc = merge(cc);

    joint(czc, cnc); 
    joint(op, ccc);

    cout << ans << '\n';
    return 0;
}