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
#include <iostream>
#include <set>

enum Color : int {
    YELLOW = 1,
    BLUE = 2,
    RED = 3,
};

struct Section {
    int begin, end;
    Color color;
    friend std::istream &operator >> (std::istream &in, Section &section) {
        return in >> section.begin >> section.end >> (int &)section.color;
    }
    friend bool compareByBegins(const Section &s1, const Section &s2) {
        return s1.begin < s2.begin || s1.begin == s2.begin && s1.end < s2.end || s1.begin == s2.begin && s1.end == s2.end && s1.color < s2.color;
    }
    friend bool compareByEnds(const Section &s1, const Section &s2) {
        return s1.end < s2.end || s1.end == s2.end && s1.begin < s2.begin || s1.end == s2.end && s1.begin == s2.begin && s1.color < s2.color;
    }
};

bool compareByBegins(const Section &s1, const Section &s2);
bool compareByEnds(const Section &s1, const Section &s2);

bool isGreen(const int levels[4]) {
    return levels[RED] == 0 and levels[YELLOW] > 0 and levels[BLUE] > 0;
}

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n, m;
    std::set<Section, decltype(compareByBegins)*> byBegins(compareByBegins);
    std::set<Section, decltype(compareByEnds)*> byEnds(compareByEnds);
    std::cin >> n >> m;
    for (int i = 0; i < m; ++i) {
        Section s{};
        std::cin >> s;
        byBegins.insert(s);
        byEnds.insert(s);
    }
    int currentLevels[4] = {0};
    int greenCans = 0, currentPos = 1;

    auto beginsIter = byBegins.begin();
    auto endsIter = byEnds.begin();
    while (endsIter != byEnds.cend()) {
        if (beginsIter != byBegins.cend() and beginsIter->begin <= endsIter->end) {
            if (isGreen(currentLevels)) {
                greenCans += beginsIter->begin - currentPos;
            }
            currentPos = beginsIter->begin;
            ++currentLevels[beginsIter->color];
            ++beginsIter;
        } else {
            if (isGreen(currentLevels)) {
                if (endsIter->end - currentPos + 1) {
                }
                greenCans += endsIter->end - currentPos + 1;
            }
            currentPos = endsIter->end + 1;
            --currentLevels[endsIter->color];
            ++endsIter;
        }
    }
    std::cout << greenCans << std::endl;
    return 0;
}