我要长高
Time Limit: 4000/2000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
韩父有 N 个儿子,分别是韩一,韩二…韩 N 。由于韩家演技功底深厚,加上他们间的密切配合,演出获得了巨大成功,票房甚至高达 2000 万。舟子是名很有威望的公知,可是他表面上两袖清风实则内心阴暗,看到韩家红红火火,嫉妒心遂起,便发微薄调侃韩二们站成一列时身高参差不齐。由于舟子的影响力,随口一句便会造成韩家的巨大损失,具体亏损是这样计算的,韩一,韩二…韩 N 站成一排,损失即为 C× (韩 i 与韩 i+1 的高度差( 1≤i<N ))之和,搞不好连女儿都赔了.韩父苦苦思索,决定给韩子们内增高(注意韩子们变矮是不科学的只能增高或什么也不做),增高 1 cm是很容易的,可是增高 10 cm花费就很大了,对任意韩 i ,增高 H cm的花费是 H2 .请你帮助韩父让韩家损失最小。
Input
有若干组数据,一直处理到文件结束。
每组数据第一行为两个整数:韩子数量 N ( 1≤N≤50000 )和舟子系数 C ( 1≤C≤100 )
接下来 N 行分别是韩i的高度( 1≤hi≤100 )。
Output
对每组测试数据用一行输出韩家的最小损失。
Sample input and output
Sample Input | Sample Output |
---|---|
5 2 2 3 5 1 4 | 15 |
</pre><pre name="code" class="cpp">#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
#define INFS 0x3fffffff
#define BG 50005
int dp[2][105];//because the best height of current one is influenced by the previous one and his real height,we must hold a dp list meaning cost of all his possible height for the next person to refer to.And this list is also generated by the nest value of function--nowf(about all the variables of last person).
int q[105];//And this best value is token by Monotonous Queue Optimization method.
int main()
{
int n,c;
int cur;
int nowf=0;
while(cin>>n>>c)//scanf("%d%d",&n,&c)!=EOF)
{
int i,j;
int res=INFS;
int tail,head;
int x=0;
cur=0;
scanf("%d",&x);
memset(q,0,sizeof(int)*105);
for(j=1;j<x;j++)
dp[cur][j]=INFS;
for(j=x;j<=100;j++)
dp[cur][j]=(x-j)*(x-j);
cur=1-cur;
for(i=2;i<=n;i++)
{
//scanf("%d",&x);
cin>>x;
//suppose the current one is taller than the previous one.
tail=head=0;//the queue q[105] is refreshed twice every time(i).
for(j=1;j<=100;j++)//j is from 1 to 100
{
nowf=dp[1-cur][j]-c*j;//the previous one
while(nowf<q[tail-1]&&head<tail)
tail--;
q[tail++]=nowf;
if(j<x)
dp[cur][j]=INFS;//the current one
else
dp[cur][j]=q[head]+c*j+(j-x)*(j-x);
}
//suppose the current one is shorter than the previous one
tail=head=0;//the second refresh
for(j=100;j>=1;j--)//j is from 100 to 1(because the previous one is taller)
{
nowf=dp[1-cur][j]+c*j;
while(nowf<q[tail-1]&&head<tail)
tail--;
q[tail++]=nowf;
if(j>=x)//the occasion where j<x is already set below.
dp[cur][j]=min(dp[cur][j],q[head]-c*j+(j-x)*(j-x));
//refresh and compare the taller occasion and the shorter occasion and fetch the smaller one.
}
cur=1-cur;//the current one becomes the previous one(for next round).
}
for(j=1;j<=100;j++)
res=min(res,dp[1-cur][j]);
printf("%d\n",res);
}
return 0;
}