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
#include <stdio.h>
#include <vector>
#include <algorithm>

using namespace std;

vector<pair<int, int>> findCommon(vector<pair<int, int>> zo, vector<pair<int, int>> ni) {
	vector<pair<int, int>> res;

	int i = 0, j = 0;
	while (i < zo.size() && j < ni.size()) {
		int a = max(zo[i].first, ni[j].first);
		int b = min(zo[i].second, ni[j].second);
		if (b >= a) res.push_back({ a, b });

		if (zo[i].second < ni[j].second) i++;
		else j++;
	}

	return res;
}

int main() {
	int n, m;
	scanf("%d%d", &n, &m);

	vector<pair<int, int>> zo, ni, cz;
	int l, r, k;
	for (int i = 0; i < m; i++) {
		scanf("%d%d%d", &l, &r, &k);
		if (k == 1) zo.push_back({ l, r });
		if (k == 2) ni.push_back({ l, r });
		if (k == 3) cz.push_back({ l, r });
	}
	sort(zo.begin(), zo.end());
	sort(ni.begin(), ni.end());
	sort(cz.begin(), cz.end());

	vector<pair<int, int>> common = findCommon(zo, ni);
	if (common.empty()) {
		printf("0");
		return 0;
	}
	int a = common[0].first, b = common[0].second, ans1 = 0;
	for (int i = 1; i < common.size(); i++) {
		if (common[i].second <= b || common[i].first <= b + 1 || common[i - 1].second == common[i].first - 1
			|| common[i].first == common[i - 1].second) {
			b = max(b, common[i].second);
		}
		else {
			ans1 += b - a + 1;
			a = common[i].first;
			b = common[i].second;
		}

		if (i == common.size() - 1) ans1 += b - a + 1;
	}
	if (ans1 == 0) ans1 += b - a + 1;

	int ans2 = 0;
	vector<pair<int, int>> commonZonicz = findCommon(common, cz);
	if (commonZonicz.empty()) {
		printf("%d", ans1);
		return 0;
	}
	a = commonZonicz[0].first, b = commonZonicz[0].second;
	for (int i = 1; i < commonZonicz.size(); i++) {
		if (commonZonicz[i].second <= b || commonZonicz[i].first <= b + 1 || commonZonicz[i - 1].second == commonZonicz[i].first - 1
			|| commonZonicz[i].first == commonZonicz[i - 1].second) {
			b = max(b, commonZonicz[i].second);
		}
		else {
			ans2 += b - a + 1;
			a = commonZonicz[i].first;
			b = commonZonicz[i].second;
		}

		if (i == commonZonicz.size() - 1) ans2 += b - a + 1;
	}
	if (ans2 == 0) ans2 += b - a + 1;

	printf("%d", ans1 - ans2);

	return 0;
}