#include #include using namespace std; using namespace atcoder; typedef long long ll; typedef long double ld; #define REP(i, n) for (int i = 0; i < (n); ++i) #define REPR(i, n) for (int i = n - 1; i >= 0; --i) #define FOR(i, m, n) for (int i = m; i < n; ++i) #define FORR(i, m, n) for (int i = m; i >= n; --i) #define ALL(v) (v).begin(),(v).end() #define ALLR(v) (v).rbegin(),(v).rend() #define fi first #define se second #define PB push_back #define EB emplace_back template using PQ = priority_queue; template using QP = priority_queue,greater>; templatevoid debug(const T &v,ll h,ll w){for(ll i=0;ivoid debug(const T &v,ll n){for(ll i=0;ivoid debug(const vector&v){debug(v,v.size());} templatevoid debug(const vector>&v){for(auto &vv:v)debug(vv,vv.size());} templatevoid debug(stack st){while(!st.empty()){cerr<void debug(queue st){while(!st.empty()){cerr<void debug(deque st){while(!st.empty()){cerr<void debug(PQ st){while(!st.empty()){cerr<void debug(QP st){while(!st.empty()){cerr<void debug(const set&v){for(auto z:v)cerr<void debug(const multiset&v){for(auto z:v)cerr<void debug(const array &a){for(auto z:a)cerr<void debug(const map&v){for(auto z:v)cerr<<"["<void foo(Head&& head, Tail&&... tail){cerr << head << " ";foo(move(tail)...);} templatebool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (b> n >> k; vector t(n),d(n); REP(i,n) cin >> t[i] >> d[i]; vector> p(n); REP(i,n) p[i]={d[i],i}; sort(ALLR(p)); vector V(n); lazy_segtree seg(V); vector b(n); for(auto [u,v]:p){ int l=upper_bound(ALL(t),t[v]-k)-t.begin(); int r=lower_bound(ALL(t),t[v]+k)-t.begin(); if(seg.prod(l,r)==1) continue; seg.apply(l,r,1); b[v]=true; } ll mx=0; REP(i,n){ if(b[i]) continue; chmax(mx,d[i]); } cout << mx << endl; vector T,D; vector ims(n+1); REP(i,n){ if(d[i]>mx){ int l=upper_bound(ALL(t),t[i]-k)-t.begin(); int r=lower_bound(ALL(t),t[i]+k)-t.begin(); ims[l]++,ims[r]--; } } int res=0; ll sum=0; REP(i,n){ res+=ims[i]; if(!res) T.PB(t[i]),D.PB(d[i]); else{ if(d[i]<=mx) sum+=d[i]; } } int m=T.size(); vector dp(m+1); ll sd=0; REP(i,m){ sd+=D[i]; int R=lower_bound(ALL(T),T[i]+k)-T.begin(); chmax(dp[R],dp[i]+D[i]); } cout << sum+sd-dp[m] << endl; }