103282024-03-30 22:49:38111Majomházcpp17Accepted 100/1001.603s16684 KiB
// Lagrangian Relaxation & Li Chao Tree

#include <bits/stdc++.h>
using namespace std;

#define int long long

#define INF (int)1e18

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int N,K;
	cin>>N>>K;
	vector<int>v(N+1),pf(N+1);
	for(int i=0;i<N;i++){
		cin>>v[i];
		pf[i+1]=pf[i]+v[i];
	}
	auto solve=[&](int y)->pair<int,int>{
		vector<int>dp(N+1,INF),cnt(N+1),t((N+1)*4);
		auto cost=[&](int s,int e)->int{
			return dp[s]+(pf[e]-pf[s])*(e-s);
		};
		auto add=[&](int i,int l,int r,int p)->void{
			while(true){
				int m=(l+r)/2;
				bool ll=cost(p,l)<cost(t[i],l);
				bool mm=cost(p,m)<cost(t[i],m);
				if(mm){
					swap(t[i],p);
				}
				if(l==r){
					break;
				}
				if(ll!=mm){
					i=i*2+1;
					r=m;
				}
				else{
					i=i*2+2;
					l=m+1;
				}
			}
		};
		auto get=[&](int i,int l,int r,int x)->int{
			int bc=INF,bi=0;
			while(true){
				int m=(l+r)/2;
				int c=cost(t[i],x);
				if(c<bc){
					bc=c;
					bi=t[i];
				}
				if(l==r){
					break;
				}
				if(x<m){
					i=i*2+1;
					r=m;
				}
				else{
					i=i*2+2;
					l=m+1;
				}
			}
			return bi;
		};
		dp[0]=-y;
		cnt[0]=-1;
		add(0,0,N,0);
		for(int i=1;i<=N;i++){
			int o=get(0,0,N,i);
			dp[i]=cost(o,i)+y;
			cnt[i]=cnt[o]+1;
			add(0,0,N,i);
		}
		return{dp[N],cnt[N]};
	};
	int l=0,h=INF;
	while(l<h){
		int m=(l+h)/2;
		auto [x,c]=solve(m);
		if(c<=K){
			h=m;
		}
		else{
			l=m+1;
		}
	}
	auto [x,c]=solve(h);
	cout<<x-c*h<<'\n';
	return 0;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1824 KiB
2Accepted61ms2680 KiB
subtask210/10
3Accepted3ms2272 KiB
4Accepted3ms2356 KiB
5Accepted3ms2484 KiB
6Accepted3ms2580 KiB
7Accepted3ms2776 KiB
subtask310/10
8Accepted7ms3160 KiB
9Accepted7ms3472 KiB
10Accepted7ms3424 KiB
11Accepted8ms3556 KiB
12Accepted8ms3768 KiB
subtask420/20
13Accepted63ms4264 KiB
14Accepted65ms4440 KiB
15Accepted68ms4284 KiB
16Accepted71ms4500 KiB
17Accepted71ms4644 KiB
18Accepted71ms4720 KiB
subtask529/29
19Accepted703ms10316 KiB
20Accepted728ms10216 KiB
21Accepted749ms10096 KiB
22Accepted759ms10300 KiB
23Accepted764ms10300 KiB
subtask631/31
24Accepted1.22s16600 KiB
25Accepted1.32s16616 KiB
26Accepted1.401s16608 KiB
27Accepted1.434s16556 KiB
28Accepted1.424s16672 KiB
29Accepted1.475s16552 KiB
30Accepted1.5s16524 KiB
31Accepted1.531s16560 KiB
32Accepted1.557s16556 KiB
33Accepted1.565s16560 KiB
34Accepted1.592s16676 KiB
35Accepted1.595s16668 KiB
36Accepted1.597s16672 KiB
37Accepted1.603s16676 KiB
38Accepted1.588s16684 KiB
39Accepted1.572s16644 KiB
40Accepted1.518s16676 KiB