hdu 3507 斜率优化

#include<iostream>
#include<string>
#include <bits/stdc++.h>
using namespace std;

int dp[500005];
int q[500005];
int sum[500005];
int head, tail, n, m;

int getDP(int i, int j)
{
        return dp[j] + m + (sum[i] - sum[j]) * (sum[i] - sum[j]);
}

int getUP(int j, int k) 
{
        return dp[j] + sum[j] * sum[j] - (dp[k] + sum[k] * sum[k]);
}

int getDOWN(int j, int k) 
{
        return 2 * (sum[j] - sum[k]);
}

int main()
{
        int i;
        while (scanf("%d%d", &n, &m) == 2)
        {
                sum[0] = dp[0] = 0;
                for (i = 1; i <= n; i++)
                {
                        scanf("%d", &sum[i]);
                        sum[i] += sum[i - 1];
                }
                head = tail = 1;
                q[tail] = 0;
                for (i = 1; i <= n; i++)
                {
                        while (head < tail && getUP(q[head + 1], q[head]) <= sum[i]*getDOWN(q[head + 1], q[head]))
                        {
                                head++;
                        }
                        dp[i] = getDP(i, q[head]);
                        while (head < tail && getUP(i, q[tail])*getDOWN(q[tail], q[tail - 1]) <= getUP(q[tail], q[tail - 1])*getDOWN(i, q[tail]))
                        {
                                tail--;
                        }
                        q[++tail] = i;
                }
                printf("%d\n", dp[n]);
        }
        return 0;
}

 

posted @ 2017-10-18 16:39  Aragaki  阅读(106)  评论(0编辑  收藏  举报