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
#include <bits/stdc++.h> 
using namespace std;
#define st first
#define nd second
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll N , c;
const int maxn = 500009;
pll a[maxn];
ll dp[maxn];
ll last[maxn];

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> N >> c;
    for(int i = 1 ; i <= N ; i++)
    {
        cin >> a[i].st >> a[i].nd;
    }

    ll pop = -1 , popans = 0;
    queue <int > UP;
    for(int i = 1; i <= N ; i++)
    {
        if(pop != a[i].st)
        {
            while(!UP.empty())
            {
                popans = max(popans, dp[UP.front()]);
                last[a[UP.front()].nd] = max(last[a[UP.front()].nd],dp[UP.front()]);
                UP.pop();
            }
        }
        dp[i] = a[i].st; 
        dp[i] = max(dp[i] , last[a[i].nd]+a[i].st);
        dp[i] = max(dp[i] , popans-c+a[i].st);

        pop = a[i].st;
        UP.push(i);
    }

    ll res = 0;
    for(int i = 1; i <= N ; i++)res = max(res,dp[i]);
    cout << res << '\n';

    
    return 0;
}