#include using namespace std; #include #include #include #include #include template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } #define rep(i,n) for (int i = 0; i < (n); ++i) typedef long long ll; typedef long double ld; typedef unsigned long long ull; using P=pair; const ll INF=1001001001; const int mod=998244353; void solve(){ int n,d; cin>>n>>d; vector>p(n,vector(2)); rep(i,n){ cin>>p[i][0]>>p[i][1]; } auto f=[&](int mid){ vectordp(n); rep(i,d){ vectorpre(n,-INF); swap(dp,pre); vectorl(n+1,-INF),r(n+1,-INF); rep(j,n){ chmax(l[j+1],max(l[j],pre[j])); } for(int j=n-1;j>=1;j--){ chmax(r[j-1],max(r[j],pre[j])); } rep(j,n){ ll mx=max(l[j],r[j]); if(mx-p[j][0]>=mid){ chmax(dp[j],mx-p[j][0]+p[j][1]); } } } rep(i,n){ if(dp[i]!=-INF){return true;} } return false; }; int l=-INF,r=0; while(r-l>1){ int mid=(l+r)/2; if(f(mid)){l=mid;} else{r=mid;} } cout<