题意
给出一个序列,没两个之间差值乘C就是亏损的钱数,可以给一些数列以一定的代价变大,不能减小,求增加方案令最后的损失最小。
思路
令dp[i][j]表示第i个人身高为j时的当前损失。
我们能得到
dp[i][j]=min(dp[i−1][k]+abs(j−k)∗C+(x[i]−j)∗(x[i]−j))
我们需要枚举的有当前的人i,当前身高j前一个人身高k,枚举前一个人身高可以用单调队列优化掉,总复杂度
O(nh)
。
代码
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define LL long long
#define lowbit(x) ((x)&(-x))
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1|1
#define MP(a, b) make_pair(a, b)
const int INF = 0x3f3f3f3f;
const int maxn = 1e5 + 7;
const double eps = 1e-8;
const int MOD = 1000000009;
const double PI = acos(-1.0);
int dp[2][110];
int n, c;
int q[110];
int head, tail, cur;
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while (scanf("%d%d", &n, &c) != EOF)
{
int x;
scanf("%d", &x);
cur = 0;
for (int i = 0; i < x; i++)
dp[cur][i] = INF;
for (int i = x; i <= 100; i++)
dp[cur][i] = (x - i) * (x - i);
for (int i = 1; i < n; i++)
{
scanf("%d", &x);
cur ^= 1;
head = tail = 0;
for (int j = 0; j <= 100; j++)
{
int num = dp[cur^1][j] - c * j;
while (head < tail && q[tail-1] > num)
tail--;
q[tail++] = num;
if (j < x)
dp[cur][j] = INF;
else
dp[cur][j] = q[head] + j * c + (x - j) * (x - j);
}
head = tail = 0;
for (int j = 100; j >= 0; j--)
{
int num = dp[cur^1][j] + j * c;
while (head < tail && q[tail-1] > num)
tail--;
q[tail++] = num;
if (j >= x)
dp[cur][j] = min(dp[cur][j], q[head] - j * c + (x - j) * (x - j));
}
}
int ans = INF;
for (int i = 0; i <= 100; i++)
ans = min(ans, dp[cur][i]);
printf("%d\n", ans);
}
return 0;
}