BZOJ4897 [Thu Summer Camp2016]成绩单 【dp】
题目链接
题解
发现我们付出的代价与区间长度无关,而与区间权值范围有关
离散化一下权值
我们设\(f[l][r][x][y]\)表示区间\([l,r]\)消到只剩权值在\([x,y]\)所需最小代价
\(f[l][r][0][0]\)即为消完的最小代价
那么
\[f[l][r][0][0] = min\{f[l][r][x][y] + a + b(w[y] - w[x])^2\}
\]
转移的话,贪心地取出区间两边在权值区间\([x,y]\)以内的数,剩下区间\([l',r']\)
如果剩余区间直接消去,可以直接计算
如果不一次消去,那么枚举断点转移即可
复杂度小常数\(O(n^5)\)
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 55,maxm = 100005,INF = 1000000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int f[maxn][maxn][maxn][maxn],n,a,b,w[maxn],c[maxn],tot;
void cmin(int& x,int y){x = min(x,y);}
int main(){
n = read(); a = read(); b = read();
REP(i,n) c[i] = w[i] = read();
sort(c + 1,c + 1 + n); tot = 1;
for (int i = 2; i <= n; i++) if (c[i] != c[tot]) c[++tot] = c[i];
for (int i = 1; i <= n; i++) w[i] = lower_bound(c + 1,c + 1 + tot,w[i]) - c;
for (int l = 1; l <= n; l++)
for (int r = l; r <= n; r++){
int mx = -INF,mn = INF;
for (int k = l; k <= r; k++)
mx = max(mx,w[k]),mn = min(mn,w[k]);
f[l][r][0][0] = a + b * (c[mx] - c[mn]) * (c[mx] - c[mn]);
for (int x = 1; x <= tot; x++)
for (int y = x; y <= tot; y++)
f[l][r][x][y] = INF;
}
for (int len = 1; len <= n; len++){
for (int l = 1; l + len - 1 <= n; l++){
int r = l + len - 1;
for (int x = 1; x <= tot; x++)
for (int y = x; y <= tot; y++){
int ll = l,rr = r;
while (ll <= r && w[ll] >= x && w[ll] <= y) ll++;
while (rr >= ll && w[rr] >= x && w[rr] <= y) rr--;
if (ll > rr) f[l][r][x][y] = 0;
else if (ll == rr) f[l][r][x][y] = a;
else {
for (int k = ll; k < rr; k++){
cmin(f[l][r][x][y],f[ll][k][x][y] + f[k + 1][rr][x][y]);
cmin(f[l][r][x][y],f[ll][k][0][0] + f[k + 1][rr][x][y]);
cmin(f[l][r][x][y],f[ll][k][x][y] + f[k + 1][rr][0][0]);
cmin(f[l][r][x][y],f[ll][rr][0][0]);
}
}
}
for (int x = 1; x <= tot; x++)
for (int y = x; y <= tot; y++)
cmin(f[l][r][0][0],a + b * (c[y] - c[x]) * (c[y] - c[x]) + f[l][r][x][y]);
}
}
printf("%d\n",f[1][n][0][0]);
return 0;
}