P3287 [SCOI2014]方伯伯的玉米田题解
dp
状态
容易想到一个状态
转移
可以用暴力来枚举
for (int k = 1; k < i; ++k)
for (int l = 0; l <= j; ++l)
if (a[k] + l <= a[i] + j) f[i][j] = max(f[i][j], f[k][l] + 1);
条件中的
#include <bits/stdc++.h>
using namespace std;
const int N = 10005;
int n, K, m, a[N], f[N][505], c[5505][505];
inline void add(const int &x, const int &y, const int &d) {
for (int i = x; i <= m; i += i & ~i + 1)
for (int j = y; j <= K + 1; j += j & ~j + 1) c[i][j] = max(c[i][j], d);
}
inline int ask(const int &x, const int &y) {
int res = 0;
for (int i = x; i; i &= i - 1)
for (int j = y; j; j &= j - 1) res = max(res, c[i][j]);
return res;
}
int main() {
scanf("%d%d", &n, &K);
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]), m = max(m, a[i]); m += K;
for (int i = 1; i <= n; ++i)
for (int j = K; ~j; --j)//这里注意要倒着循环,因为小的j的更新会影响到大的。
add(a[i] + j, j + 1, f[i][j] = ask(a[i] + j, j + 1) + 1);
printf("%d", ask(m, K + 1));
return 0;
}
时间复杂度
可以发现在求二维前缀和时,每一行从左到右是单调不降的,每一列从上到下也是单调不降的。所以对于
#include <bits/stdc++.h>
using namespace std;
const int N = 10005;
int n, K, m, a[N], c[2][5505][505];
inline void add(const int &x, const int &y, const int &d) {
for (int i = x; i <= m; i += i & ~i + 1) c[0][i][y] = max(c[0][i][y], d);
for (int i = y; i <= K + 1; i += i & ~i + 1) c[1][x][i] = max(c[1][x][i], d);
}
inline int ask(const int &x, const int &y) {
int res = 0;
for (int i = x; i; i &= i - 1) res = max(res, c[0][i][y]);
for (int i = y; i; i &= i - 1) res = max(res, c[1][x][i]);
return res;
}
int main() {
scanf("%d%d", &n, &K);
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]), m = max(m, a[i]); m += K;
for (int i = 1; i <= n; ++i)
for (int j = K; ~j; --j)//这里正序倒序循环都没关系
add(a[i] + j, j + 1, ask(a[i] + j, j + 1) + 1);
printf("%d", ask(m, K + 1));
return 0;
}
时间复杂度