数据范围$n\leqslant 10,000, m \leqslant 1,000$,写$O(nm)$的背包完全是可以通过本题的。对于上升是一个完全背包,对于下降是一个01背包,则有
$$f[i][j] = min(f[i-1][j-x[i-1]]+1, f[i][j-x[i-1]]+1, f[i-1][j+y[i-1]])$$
如何实现别的题解说明的很清楚我也不再赘述
同学都知道一般背包是有压维写法的,数组大小开到$10,000*1,000$怎么说都有点勉强~~并不勉强只是想优化~~,来考虑一下压维要实现的一些细节,压维以后的方程式是这样的
$$f[j] = min(f[j-x[i-1]]+1, f[j+y[i-1]])$$
而对于$f[j-x[i-1]]$实际上包含的是两个状态,分别是$f[i-1][j-x[i-1]]$和$f[i][j-x[i-1]]$所以可以新建两个辅助数组,分别存下两个状态,最后结果要在两个中间取
至于枚举顺序就像完全背包一样从小到大枚举就行枚举到$j$时$f[j+y[i-1]]$存的状态$f[i-1][j+y[i-1]]$所以并不需要拿数组暂存
$$f_1[j] = min(f_1[j-x[i-1]]+1, f[j-x[i-1]]+1)$$
$$f_2[j] = f[j+y[i-1]]$$
$$f[j]=min(f_1[j], f_2[j])$$
对于$f_1$表示该高度由跳跃而来的最小步数,对于$f_2$表示由降落而来的最小步数
这样就成功的把时间复杂度为$O(nm)$的空间复杂度优化为$O(m)$
```
//2019/2/2->NHDR233->AtHM->luoguP1941
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<time.h>
using namespace std;
inline int in() {
int x = 0, ch = getchar();
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) x = x*10+ch-‘0‘, ch = getchar();
return x;
}
void input();
void smin(int& x, int y) {
if (x > y) x = y;
}
const int TOP = 10100, INF = 1e9;
int n, m, k;
int x[TOP], y[TOP<<1], ans[TOP<<1], tem1[TOP], tem2[TOP];
struct node{
int where, down, top;
} s[TOP];
bool cmp(node a, node b) {
return a.where < b.where;
}
void work() {
sort(s+1, s+k+1, cmp);
int now = 1;
for (int i = m+1; i <= 2*m; ++i) ans[i] = INF;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= 2*m; ++j)
tem1[j] = ans[j];
bool flag = false;
for (int j = 1; j <= m; ++j) {
tem2[j] = INF;
if (j > x[i-1]) {
smin(tem2[j], tem1[j-x[i-1]]+1);
smin(tem2[j], tem2[j-x[i-1]]+1);
}
ans[j] = min(tem2[j], tem1[j+y[i-1]]);
}
for (int j = 0; j <= x[i-1]; ++j) {
smin(ans[m], tem1[m-j]+1);
smin(ans[m], tem2[m-j]+1);
}
if (s[now].where == i) {
for (int j = 1; j <= m; ++j) {
if (j > s[now].down and j < s[now].top) continue;
ans[j] = INF;
}
now++;
}
for (int j = 1; j <= m; ++j) {
if (ans[j] < INF) flag = true;
}
if (!flag) {
printf("0\n%d", now-2);
return;
}
}
int final = INF;
for (int i = 1; i <= m; ++i) {
smin(final, ans[i]);
}
printf("1\n%d", final);
}
int main() {
input();
work();
}
void input() {
n = in(); m = in(); k = in();
for (int i = 0; i < n; ++i) {
x[i] = in(); y[i] = in();
}
for (int i = 1; i <= k; ++i) {
s[i].where = in();
s[i].down = in();
s[i].top = in();
}
}
```
原文地址:https://www.cnblogs.com/NHDR233/p/11246702.html