数据比较弱,所以dfs可以过。很好想每个板子都可以分成横着刷和纵着刷,可以写出递推方程
f( l , r, h ) = min( r - l + 1 , f( l, p-1, a[p]) + f(p+1, r, a[p]) + a[p] - h)
p 为 [ l , r ] 中最小值的下标,暴力求解可以过
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define INF (int)(1e9)
#define maxn 5010
using namespace std;
typedef long long ll;
int a[maxn];
int find_min(int l, int r) {
int ix, res = INF+10;
for (int i = l; i <= r; ++ i) {
if (a[i] < res) {
ix = i;
res = a[i];
}
}
return ix;
}
int dfs(int l, int r, int h) {
if (l > r) return 0;
int ix = find_min(l,r);
int m = a[ix];
return min(r-l+1, dfs(l,ix-1,m) + dfs(ix+1,r,m)+m-h);
}
int main() {
int n;
while (cin >> n) {
for (int i = 0; i < n; ++ i) {
cin >> a[i];
}
cout << dfs(0,n-1,0) << endl;
}
}
可以使用RMQ优化求最小值的过程
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define INF (int)(1e9)
#define maxn 100010
using namespace std;
typedef long long ll;
int a[maxn], f[maxn][100];
void RMQ_init(int n) {
for (int i = 1; i <= n; ++ i) f[i][0] = a[i];
for (int j = 1; j <= int( log(double(n))/log(2.0) ); ++ j)
for (int i = 1; i <= n-(1<<(j-1)); ++ i)
f[i][j] = min(f[i][j-1],f[i+(1<<(j-1))][j-1]);
}
int RMQ(int L, int R) {
int t = int( log(double(R-L+1))/log(2.0) );
return min(f[L][t],f[R+1-(1<<t)][t]);
}
int dfs(int l, int r, int h) {
if (l > r) return 0;
int ix = RMQ(l,r);
int m = a[ix];
return min(r-l+1, dfs(l,ix-1,m) + dfs(ix+1,r,m)+m-h);
}
int main() {
int n;
while (cin >> n) {
for (int i = 1; i <= n; ++ i) {
cin >> a[i];
}
RMQ_init(n);
cout << dfs(1,n,0) << endl;
}
}