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
#include <bits/stdc++.h>
#define ll long long
using namespace std;

int n;
ll c;
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> c;

    //vector<pair<int, int>> blocks(n);

    vector<pair<int, vector<int>>> blockGroups;

    for(int i = 0; i < n; i++)
    {
        pair<int, int> curr;
        //cin >> blocks[i].first >> blocks[i].second;
        cin >> curr.first >> curr.second;
        if(blockGroups.empty() || blockGroups.back().first != curr.first)
            blockGroups.push_back({curr.first, { curr.second } });
        else
            blockGroups.back().second.push_back(curr.second);
    }
    
    ll result = -1;

    //najlepszy wynik dla danego wzorku
    vector<ll> colorBest(500002, 0);
    //           val  wzor
    vector<pair<ll, int>> dp(n, {0, 0});

    int bestColor = -1;

    ll currMaxValue = 0;

    int idx = 0;
    for(int x = blockGroups.size() - 1; x >= 0; x--)
    {
        ll currSize = blockGroups[x].first;

        int startIdx = idx;
        for(int currColor : blockGroups[x].second)
        {
            //albo dokładamy do tego samego wzoru, albo do innego, albo osobno calkowicie
            //               sam klocek        dokladamy do wzoru       do maksymalnej wartosci
            ll currDp = max(currSize, max( colorBest[currColor] + currSize, currMaxValue + currSize - c));
            dp[idx] = {currDp, currColor};
            idx++;
        }

        for(int i = startIdx; i < idx; i++)
        {
            currMaxValue = max(currMaxValue, dp[i].first);
            colorBest[dp[i].second] = max(colorBest[dp[i].second], dp[i].first);
        }
    }

    cout << currMaxValue;

    /* int prev = -1;
    for(int i = 0; i < n; i++)
    {

        //albo dokładamy do tego samego wzoru, albo do innego, albo osobno calkowicie
        //                  sam klocek                   dokladamy do wzoru                           do maksymalnej wartosci
        ll currDp = max((ll)blocks[i].first, max( dp[blocks[i].second] + (ll)blocks[i].first, currMaxValue + (ll)blocks[i].first - c));

        currMaxValue = max(currMaxValue, currDp);
        dp[blocks[i].second] = max(dp[blocks[i].second], currDp);

    } */
    return 0;
}