#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int n,k;
int minn = 1e9;//最小值
int ltor,rtor,pt; //左力矩、右力矩、切割點
vector<int> prex;//前綴和
vector<int> sufx;//後綴和
LL solve(vector<int> &lis,int st,int ed,int k){
//cout<<st<<" "<<ed<<endl;
if(k==0) return 0;
if(abs(ed-st) < 3) return 0;
else{
prex.clear();
prex.push_back(lis[st]);
for(int i=st+1;i<ed;i++) prex.push_back(lis[i]+prex[i-1]);
sufx.clear();
sufx.push_back(prex[ed-st-1]);
for(int i=st+1;i<ed;i++)sufx.push_back(sufx[i-st-1]-lis[i-1]);
minn = 1e9;
ltor = 0;rtor = 0;
for(int i=st+1;i<ed;i++)rtor += lis[i]*(i-st);
pt = 0;
for(int i=st+1;i<ed-1;i++){//支點範圍
ltor += prex[i-1];
rtor -= sufx[i];
cout<<"ltor = "<<ltor<<", rtor = "<<rtor<<endl;
if(abs(rtor - ltor)<minn){
minn = abs(rtor - ltor);
pt = i;
}
}
//cout<<st<<" "<<pt<<" "<<pt+1<<" "<<ed<<endl;
}
return lis[pt] + solve(lis,st,pt,k-1) + solve(lis,pt+1,ed,k-1);
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(0);
cin>>n>>k;
vector<int> arr(n);
for(int i=0;i<n;i++) cin>>arr[i];
cout<<solve(arr,0,n,k);
}
我的想法是
以範例測資為例
7 3 2 4 1 3 7 6 9
我以為會分成
(2),4,(1,3),7,(6,9)
結果我發現會多出
(1,3,7,6,9)
我不知道如何解決