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
#include <algorithm>
#include <iostream>
#include <iso646.h>
#include <stdlib.h>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <chrono>
#include <limits>
#include <random>
#include <string>
#include <time.h>
#include <thread>
#include <vector>
#include <cmath>
#include <queue>
#include <tuple>
#include <set>
#include <map>

using namespace std;

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

int n_tow, pun;
pair<int, int> max_val = {1, 0};

cin >> n_tow >> pun;

vector<int> heights(n_tow + 1);

vector<int> color(n_tow + 1);


for(int i = 1; i <= n_tow; i++)
{
    cin >> heights[i] >> color[i];
}

vector<pair<int, int>> DP(500001);

for(int i = 1; i <= n_tow; i++)
{
    if(DP[color[i]].first != heights[i])
    {
        DP[color[i]].second = DP[color[i]].second + heights[i];
        DP[color[i]].first = heights[i];
    }

    if(max_val.first == heights[i])
    {
        max_val = max(DP[color[i]], max_val);
    }
    else
    {
        if(DP[color[i]].second > max_val.second + heights[i] - pun)
        {
            max_val.second = DP[color[i]].second;
            max_val.first = DP[color[i]].first;
        } 
        else if(max_val.second < max_val.second + heights[i] - pun)
        {
            max_val.second = max_val.second + heights[i] - pun;
            max_val.first = heights[i];
        }

    }
}

cout << max_val.second;

return 0;
}
/*
4 1
1 1
3 2
4 3
4 1

4 5
1 1
3 2
4 3
4 1
*/