#include #include #include #include #include #define repeat(i,n) for (int i = 0; (i) < (n); ++(i)) #define whole(f,x,...) ([&](decltype((x)) whole) { return (f)(begin(whole), end(whole), ## __VA_ARGS__); })(x) typedef long long ll; using namespace std; template void setmax(T & a, T const & b) { if (a < b) a = b; } const ll inf = ll(1e18)+9; int main() { // input int n, k; cin >> n >> k; vector t(n+1), d(n); { t[0] = - k; repeat (i,n) cin >> t[i+1] >> d[i]; } // compute ll sum_d = whole(accumulate, d, 0ll); auto func = [&](ll limit) { vector dp(n+1, - inf); // dp dp[0] = 0; int last = 0; repeat (i,n) { int j = (whole(upper_bound, t, t[i+1]-k) - 1) - t.begin(); assert (t[i+1] - t[j] >= k); if (d[i] <= limit) { dp[i+1] = dp[i]; if (last <= j) setmax(dp[i+1], dp[j] + d[i]); } else { if (j < last) return inf; dp[i+1] = dp[j] + d[i]; last = i+1; } assert (dp[i+1] <= inf); } return sum_d - dp[n]; }; vector sorted_d = d; sorted_d.push_back(-1); sorted_d.push_back(0); whole(sort, sorted_d); sorted_d.erase(whole(unique, sorted_d), sorted_d.end()); int l = 0, r = n+1; // (l, r], binary search while (l+1 < r) { int m = (l + r) / 2; (func(sorted_d[m]) < inf ? r : l) = m; } // output ll limit = sorted_d[r]; cout << limit << endl; cout << func(limit) << endl; return 0; }