码迷,mamicode.com
首页 > 其他好文 > 详细

bzoj3675

时间:2017-06-26 21:08:50      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:int   分割   using   double   技术分享   alt   scanf   const   ace   

斜率优化

那个并查集还是A不掉,就做一些其他的。

一开始并不能写出dp方程,但是有这个结论,分割的顺序不影响答案,那么就很好写出了。

dp[i][k]=dp[j][k-1]+(sum[i]-sum[j])*sum[j] 因为顺序不影响答案,所以我们就可以看成从后往前一段一段割,所以就是先割掉i,再割掉j。

然后就是斜率优化了,我还是搞不懂什么时候用上凸壳。。。

技术分享
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100010;
int n, K, pre;
int q[N];
ll a[N], sum[N], dp[N][2];
double slope(int i, int j)
{
    if(sum[j] == sum[i]) return dp[i][pre ^ 1] - dp[j][pre ^ 1] + sum[j] * sum[j] - sum[i] * sum[i] > 0 ? 1e9 : -1e9;
    return (double)(dp[i][pre ^ 1] - dp[j][pre ^ 1] + sum[j] * sum[j] - sum[i] * sum[i]) / (double)(sum[j] - sum[i]);
}
int main()
{
    scanf("%d%d", &n, &K);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%lld", &a[i]);
        sum[i] = sum[i - 1] + a[i];
    }
    for(int k = 1; k <= K; ++k)
    {
        int l = 1, r = 0;
        q[++r] = 0;
        for(int i = 1; i <= n; ++i)
        {
//            printf("q[%d]=%d q[%d]=%d\n", l, q[l], r, q[r]);
            while(l < r && slope(q[l], q[l + 1]) < (double)sum[i]) ++l;
            dp[i][pre] = dp[q[l]][pre ^ 1] + (sum[i] - sum[q[l]]) * sum[q[l]];
            while(l < r && slope(q[r], i) < slope(q[r - 1], q[r])) --r;
            q[++r] = i;  
        }
        pre ^= 1;
    }
    printf("%lld\n", dp[n][pre ^ 1]);
    return 0;
}
View Code

 

bzoj3675

标签:int   分割   using   double   技术分享   alt   scanf   const   ace   

原文地址:http://www.cnblogs.com/19992147orz/p/7082301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!