1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include<algorithm> #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> #include<vector> #include<cstdio> #include<cmath> #include<queue> using namespace std;
typedef long long LL;
namespace FastIO { const int L=1<<15; char buf[L],*S,*T; char getchar() { if(S==T) {T=(S=buf)+fread(buf,1,L,stdin);if(S==T)return EOF;} return *S++; } LL Get_Int() { LL res=0,bj=1;char c=getchar(); while(!isdigit(c)) {if(c=='-')bj=-1;c=getchar();} while(isdigit(c)) {res=res*10+c-'0';c=getchar();} return res*bj; } } using FastIO::Get_Int;
const int maxn=100005,maxk=2;
int n,m,Q[maxn]; LL sum[maxn],f[maxn][maxk];
double Up(int i,int j,int con) { return (double)(f[j][con]-sum[j]*sum[n]-(f[i][con]-sum[i]*sum[n])); }
LL Down(int i,int j) { return (sum[j]-sum[i]); }
int main() { n=Get_Int(); m=Get_Int()+1; for(int i=1; i<=n; i++)sum[i]=sum[i-1]+Get_Int(); for(int j=1; j<=m; j++) { int Left=1,Right=1; Q[1]=0; f[0][j&1]=0; for(int i=1; i<=n; i++) { while(Left<Right&&Up(Q[Left],Q[Left+1],(j-1)&1)>=-sum[i]*Down(Q[Left],Q[Left+1]))Left++; int Front=Q[Left]; f[i][j&1]=f[Front][(j-1)&1]+(sum[i]-sum[Front])*(sum[n]-sum[i]); while(Left<Right&&Up(Q[Right-1],Q[Right],(j-1)&1)*Down(Q[Right],i)<=Up(Q[Right],i,(j-1)&1)*Down(Q[Right-1],Q[Right]))Right--; Q[++Right]=i; } } printf("%lld\n",f[n][m&1]); return 0; }
|