[BZOJ3675] [Apio2014]序列分割
[BZOJ3675] [Apio2014]序列分割
题目链接
https://www.lydsy.com/JudgeOnline/problem.php?id=3675
https://www.luogu.org/problemnew/show/P3648
Solution
考虑乘法分配律,显然从右到左合并和任意顺序合并本质相同,那么容易得到一个普及组的\(\rm dp\):
\[f[i][j]=\max_{k=1}^{i-1}\{f[k][j-1]+s_k(s_i-s_k)\}
\]
其中\(f[i][j]\)表示前\(i\)个,合并了\(j\)块的最大值。
那么直接大力斜率优化就好了,复杂度\(O(nk)\)。
注意洛谷要输出方案,直接记一下当前状态从哪里转移过来就好了。
Code
#include<bits/stdc++.h>
using namespace std;
#define int long long
void read(int &x) {
x=0;int f=1;char ch=getchar();
for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-f;
for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';x*=f;
}
void print(int x) {
if(x<0) putchar('-'),x=-x;
if(!x) return ;print(x/10),putchar(x%10+48);
}
void write(int x) {if(!x) putchar('0');else print(x);putchar('\n');}
#define lf double
#define ll long long
#define pii pair<int,int >
#define vec vector<int >
#define pb push_back
#define mp make_pair
#define fr first
#define sc second
#define FOR(i,l,r) for(int i=l,i##_r=r;i<=i##_r;i++)
const int maxn = 2e5+10;
const int inf = 0x7f7f7f7f;
const lf eps = 1e-8;
const int mod = 1e9+7;
int n,k,s[maxn],f[maxn][2],q[maxn],h,t;//,p[maxn][201];
#define sqr(x) ((x)*(x))
lf slope(int i,int j,int k) {return s[i]==s[j]?inf:(lf)((sqr(s[j])-f[j][k&1])-(sqr(s[i])-f[i][k&1]))/(s[j]-s[i]);}
signed main() {
read(n),read(k);for(int i=1,x;i<=n;i++) read(x),s[i]=s[i-1]+x;
for(int j=1;j<=k;j++) {
h=t=1;q[t]=0;
for(int i=1;i<=n;i++) {
while(h<t&&slope(q[h],q[h+1],j-1)<s[i]) h++;
f[i][j&1]=f[q[h]][j&1^1]+s[q[h]]*(s[i]-s[q[h]]);
//p[i][j]=q[h];
while(h<t&&slope(i,q[t],j-1)<slope(q[t],q[t-1],j-1)) t--;
q[++t]=i;
}
}write(f[n][k&1]);int x=n;
// for(int i=k;i;i--) printf("%d ",p[x][i]),x=p[x][i];
return 0;
}