2015
05-23

# Covered Walkway

Your university wants to build a new walkway, and they want at least part of it to be covered. There are certain points which must be covered. It doesn’t matter if other points along the walkway are covered or not.
The building contractor has an interesting pricing scheme. To cover the walkway from a point at x to a point at y, they will charge c+(x-y)2, where c is a constant. Note that it is possible for x=y. If so, then the contractor would simply charge c.
Given the points along the walkway and the constant c, what is the minimum cost to cover the walkway?

There will be several test cases in the input. Each test case will begin with a line with two integers, n (1≤n≤1,000,000) and c (1≤c≤109), where n is the number of points which must be covered, and c is the contractor’s constant. Each of the following n lines will contain a single integer, representing a point along the walkway that must be covered. The points will be in order, from smallest to largest. All of the points will be in the range from 1 to 109, inclusive. The input will end with a line with two 0s.

There will be several test cases in the input. Each test case will begin with a line with two integers, n (1≤n≤1,000,000) and c (1≤c≤109), where n is the number of points which must be covered, and c is the contractor’s constant. Each of the following n lines will contain a single integer, representing a point along the walkway that must be covered. The points will be in order, from smallest to largest. All of the points will be in the range from 1 to 109, inclusive. The input will end with a line with two 0s.

10 5000
1
23
45
67
101
124
560
789
990
1019
0 0

30726

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

Idea：

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

（画图慢慢观察下，可参考另外一题：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;
{
f[i] = temp;
}
}
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 了
*/