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 <bits/stdc++.h>

// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2")

#define int long long

using namespace std;

constexpr int INF = numeric_limits<int>::max();

int32_t main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	int n, c;
	cin >> n >> c;
	vector<pair<int, int>> klocki;
	unordered_set<int> set_klocki;
	int last_kloc = -1;
	for (int i = 0; i < n; i++)
	{
		int a, w;
		cin >> a >> w;
		if (a != last_kloc)
		{
			set_klocki.clear();
		}

		if (set_klocki.find(w) == set_klocki.end())
		{
			klocki.push_back({a, w});
			set_klocki.insert(w);
		}
		last_kloc = a;
	}
	n = klocki.size();

	vector<int> min_tab(500001, 0);
	vector<int> min_total(2, 0);
	int czytam = 0;

	int odp = 0;

	for (int i = 0; i < n; i++)
	{
		if (i != 0 && klocki[i].first != klocki[i - 1].first)
		{
			czytam = (czytam + 1) % 2;
		}
		int pisze = (czytam + 1) % 2;
		// cerr << "klocek " << i << ", czytam " << czytam << endl;
		// edge to any is -klocki[i].second + c
		// edge to matching color is -klocki[i].second

		auto kloc = klocki[i];
		int wzor = kloc.second;
		int bok = kloc.first;

		int curr = min(min_total[czytam] - bok + c, min_tab[wzor] - bok);
		odp = max(odp, -curr);

		min_total[pisze] = min(min(min_total[czytam], curr), min_total[pisze]);
		min_tab[wzor] = min(min_tab[wzor], curr);
	}

	cout << odp << endl;
}