HDU 4258 Covered Walkway (DP +数形结合)#by Plato 终于A出来了~~~~~

http://acm.hdu.edu.cn/showproblem.php?pid=4258

题意:一个N个点的序列,要将他们全部覆盖,求总最少费用;费用计算: c+(x-y)2

Idea:

朴素的想法: f[i] = min(f[j] + (a[i]-a[j+1]) ^ 2+c) (N^2)

公式变形+数形结合:f[i] = min{f[j] + a[j+1]^2 - 2*a[i]*a[j+1] + a[i]^2 +C}

令x = a[j+1],y = f[j] + a[j+1]^2;

f[i] = y - 2*a[i]*x + a[i]^2 + C;

问题转化为: 已知直线的斜率为a[i],求过前i-1个点直线与y轴的最小截距。

最后优化:经过一系列的推理,可以得到--用下凸曲线来维护检查集,可以在均摊O(1)的时间内,找到斜率连续变化时的最小值。

(画图慢慢观察下,可参考另外一题:http://blog.csdn.net/xdu_truth/article/details/7943237)


#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int N,C;
long long a[1000010];//int a[1000010]   要么用long long,要么每次算平方是将其转化为long long
long long f[1000010];

struct point
{
    int id;
    long long  x,y;
    point(int a,long long b,long long c)
    {
        id = a;x = b;y = c;
    }
    point(){};
};

long long  solve()
{
    static point s[1000010];
    int head = 1,tail = 0;
    long long temp;

    for (int i = 1;i <= N;i++)
    {
        point p(i-1,a[i],f[i-1]+ a[i]*a[i]);
        while(tail-1 >= head && (s[tail].x - s[tail-1].x)*(p.y - s[tail].y) - (s[tail].y - s[tail-1].y) *(p.x - s[tail].x) <0)//while (tail >= head...
            tail --;
        s[++tail] = p;
        while (head <= tail && (temp = s[head].y - 2*a[i]*s[head].x+a[i]*a[i] + C,temp < f[i]||f[i] == -1))//while(temp = s[head].y - 2*a[i]*s[head].x+a[i]*a[i] + C,temp < f[i]||f[i] == -1)
        {
            f[i] = temp;
            head++;
        }
        head--;
    }
    return f[N];
}

int main()
{
    freopen("test.txt","r",stdin);
    while(scanf("%d%d",&N,&C),N+C)
    {
        a[0] = 0;//a[0] = f[0] = 0;
        for(int i = 1;i <= N;i++)
            scanf("%d",&a[i]);

        memset(f,-1,sizeof(f));
        f[0] = 0;
        printf("%I64d\n",solve());
    }

    return 0;
}
/*
example:比ans要少1,观察了下,发现f[0]的初始化有问题
1st/WA:代码表达出错,检查下凸曲线部分写错了,说明思维还不够清晰;
2nd/WA:下凸数组没有进行防越界处理
3rd/WA;这次是由于计算过程中有两个较大的int相乘,编译是默认结果也是用int保存,导致溢出。然后就把数据都改成long long 了
*/


你可能感兴趣的:(c,优化,struct,idea)