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

vector<pair<int,int>> v;

long long result = 0;
long long wzorki[500005];

int main(){
    ios_base::sync_with_stdio(0);
    int n,k; cin >> n >> k;
    for(int i=0;i<n;i++){
        int a,b; cin >> a >> b;
        v.push_back({a,b});
    }
    sort(v.begin(),v.end(),greater<pair<int,int>>());
    long long tempresult=0;
    for(int i=0;i<n;i++){
        if(i>0&&v[i]==v[i-1]) continue;
        if(i>0&&v[i].first!=v[i-1].first){
            result = max(result,tempresult);
            tempresult = 0;
        }
        long long contender = max(result+v[i].first-k, wzorki[v[i].second]+v[i].first);
        wzorki[v[i].second] = contender;
        tempresult = max(tempresult,contender);
    }
    result = max(result,tempresult);
    cout << result;
}