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
#include <bits/stdc++.h>
using namespace std;
const long long NEG_INF = -1000000000000000000LL;

int main() 
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int n, c; 
    cin>>n>>c;
    vector<pair<int,int>>tab(n);
    for(int i=0;i<n;i++)cin>>tab[i].first>>tab[i].second;
    vector<long long> dp(500001, NEG_INF);
    vector<int>pom1; vector<long long>pom2;
    long long wyn=0,dp_war,g1=NEG_INF,g2=NEG_INF;
    int g3=-1,j;
    for (int i = 0; i < n; i++){
        j=i;
        pom1.clear();pom2.clear();
        while(j<n&&tab[j].first==tab[i].first){
            dp_war=tab[j].first;
            if(g3==tab[j].second){
                if(g2 == NEG_INF)dp_war+=max({0LL,dp[tab[j].second],g2});
                else dp_war+=max({0LL,dp[tab[j].second],g2-c});
            }
            else{
                if(g1==NEG_INF)dp_war+=max({0LL,dp[tab[j].second],g1});
                else dp_war+=max({0LL,dp[tab[j].second],g1-c});
            }
            pom2.push_back(dp_war);
            pom1.push_back(tab[j].second);  
            wyn=max(wyn,dp_war);
            j++;
        }
        unordered_map<int,long long>naj; naj.reserve(pom2.size()*2);
        for (size_t k=0;k<pom2.size();k++){
            if(naj.find(pom1[k])==naj.end())naj[pom1[k]]=pom2[k];
            else naj[pom1[k]]=max(pom2[k],naj[pom1[k]]);
        }
        for(auto &x:naj)dp[x.first]=max(dp[x.first],x.second);
        for(auto &x:naj){
            if(x.second>g1){
                if(x.first==g3)g1=x.second;
                else{
                    g2=g1;
                    g1=x.second;
                    g3=x.first;
                }
            }
            else if(x.first!=g3&&x.second>g2)g2=x.second;
        }
        i=j-1;
    }
    cout<<wyn;
    return 0;
}