This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const long long maxn=100001;
long long n,k;
long long a[maxn];
long long dp[maxn];
long long p[maxn];
void read()
{
cin>>n>>k;
for(long long i=1; i<=n; i++)
{
cin>>a[i];
p[i]=p[i-1]+a[i];
}
}
int idx[maxn][201];
vector<long long> ans;
void rec(long long i,long long c)
{
if(c==0)return;
ans.push_back(idx[i][c]);
rec(idx[i][c],c-1);
}
struct line
{
long long a,b,id;//a*x + b;
line() {}
line(long long _a,long long _b,long long _id)
{
a=_a;
b=_b;
id=_id;
}
long long v(long long x)
{
return a*x+b;
}
};
deque<line> d1,d2;
double pt(line l1,line l2)
{
return (double)(l2.b-l1.b)/(double)(l1.a-l2.a);
}
void push_line(line l)
{
while(d2.size()>1&&pt(l,d2[d2.size()-1])<=pt(l,d2[d2.size()-2]))d2.pop_back();
d2.push_back(l);
}
long long curr=0;
pair<long long,long long> query(long long x,long long idq)
{
long long ii=0;
long long ans=-1,id=0;
for(long long i=curr; i<d1.size(); i++)
{
if(d1[i].id<idq&&ans<=d1[i].v(x))
{
ans=d1[i].v(x);
id=d1[i].id;
ii=i;
}
else break;
}
curr=ii;
return {ans,id};
}
void solve()
{
for(long long i=1; i<=n; i++)
push_line({p[i],-p[i]*p[i],i});
d1=d2;
d2.clear();
for(long long j=1; j<=k; j++)
{
curr=0;
//cout<<"! "<<j<<endl;
for(long long i=1; i<=n; i++)
{
pair<long long,long long> in=query(p[i],i);
//cout<<i<<" "<<in.first<<" "<<in.second<<endl;
dp[i]=in.first;
idx[i][j]=in.second;
push_line({p[i],dp[i]-p[i]*p[i],i});
/*for(long long l=0; l<i; l++)
{
long long curr=dp1[l][j-1]+(p[i]-p[l])*p[l];
if(dp1[i][j]<=curr)
{
dp1[i][j]=curr;
idx[i][j]=l;
}
}*/
//cout<<i<<" "<<dp1[i][j]<<endl;
}
d1=d2;
d2.clear();
}
cout<<dp[n]<<'\n';
rec(n,k);
for(long long i=k-1; i>=0; i--)
cout<<ans[i]<<" ";
cout<<'\n';
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
read();
solve();
return 0;
}
/*
7 3
4 1 3 4 0 2 3
10 1
1 1 0 0 0 0 0 0 0 0
*/
Compilation message (stderr)
sequence.cpp: In function 'std::pair<long long int, long long int> query(long long int, long long int)':
sequence.cpp:69:28: warning: comparison of integer expressions of different signedness: 'long long int' and 'std::deque<line>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
69 | for(long long i=curr; i<d1.size(); i++)
| ~^~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |