题目链接:http://uoj.ac/problem/104
设
fi,j
为对前
j
个元素切割
fi,j=
max{
fi−1,k+sumk∗(sumi−sumk)
}
记 Xk=sumk,Yk=−sumk∗sumk+fi,k
fi,j= max{ sumi∗Xk+Yk },斜率优化即可。
WA:维护凸包写错了。。。 以及超出空间限制。。。
AC:http://uoj.ac/submission/16864
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define Calc(A,k) (A.x * (k) + A.y)
#define ConCross(A,B,C) (long double)(B.x-A.x)*(C.y-A.y)- (long double)(C.x-A.x)*(B.y-A.y)
const int MAXN = 1e5+5, MAXK = 205;
int n, k, sum[MAXN];
struct Node
{
long long f,x,y;
void Getxy(int t)
{x = sum[t] ,y = f -(long long)sum[t]*sum[t];}
};
Node g[2][MAXN];int flag = 0;
int dec[MAXK][MAXN];
int line[MAXN], f, r;
template<typename Number>void read(Number &x)
{
x = 0;char c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9')
x = (x<<3) + (x<<1) + (c-'0'), c = getchar();
}
template<typename Number>void write(Number x)
{
static char s[25];int sl = 0;
while(x) s[++sl] = x%10 + '0',x /= 10;
if(!sl) {putchar('0');return;}
while(sl) putchar(s[sl--]);
}
void GetMethod(int p,int q)
{
if(dec[p][q]) GetMethod(p - 1,dec[p][q]);
write(q), putchar(' ');
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("uoj104.in","r",stdin);
freopen("uoj104.out","w",stdout);
#endif
read(n), read(k);
for(int i = 1, ai; i <= n; i++)
read(ai), sum[i] = sum[i-1] + ai;
for(int j = 0; j <= n; j++)
g[0][j].x = sum[j], g[0][j].y = -(long long)sum[j]*sum[j];
flag = 0;
for(int i = 1 ; i <= k; i++)
{
f = r = 0, line[r ++] = i;
flag ^= 1;
for(int j = i + 1; j <= n; j++)
{
while(r - f > 1 && Calc(g[flag^1][line[f]],sum[j]) <= Calc(g[flag^1][line[f+1]],sum[j])) f ++;
g[flag][j].f = Calc(g[flag^1][line[f]],sum[j]);
dec[i][j] = line[f], g[flag][j].Getxy(j);
while(r - f > 1 && ConCross(g[flag^1][line[r-2]],g[flag^1][line[r-1]],g[flag^1][j]) >= 0) r --;
line[r ++] = j;
}
}
write(g[flag][n].f), puts("");
GetMethod(k - 1 ,dec[k][n]);
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}