这道题discuss上说是DP题。感觉我的解法更像是搜索加剪枝。
由于爬的最大高度只有1000,我们可以开个DP[40][1000]数组记录爬过的最大高度。DP[i][m]表示当前在第i步,当前高度是m,从第0步爬到i步的过程中最大高度的最小值是DP[i][m]。每次如果能够降低DP[i][m],我们就继续,否则就不用往下尝试了(只可能更差)。
所以我的总体思路完全是搜索加剪枝,一步步往下走,更新DP[i][m]。
2397和这道题是重复的。
thestoryofsnow | 3003 | Accepted | 364K | 16MS | C++ | 1951B |
/*
ID: thestor1
LANG: C++
TASK: poj3003
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>
using namespace std;
const int MAXM = 40 + 1;
const int MAXD = 1000 + 1;
void func(int i, int d, int nd, bool up, int DP[][MAXD], bool step[][MAXD], int distances[], const int M)
{
if (d < 0 || nd >= DP[i][d])
{
return;
}
DP[i][d] = nd;
step[i][d] = up;
if (i == M - 1)
{
return;
}
func(i + 1, d - distances[i + 1], max(nd, d - distances[i + 1]), false, DP, step, distances, M);
func(i + 1, d + distances[i + 1], max(nd, d + distances[i + 1]), true, DP, step, distances, M);
}
void buildSolution(char solution[], bool step[][MAXD], int distances[], const int M)
{
int d = 0;
for (int i = M - 1; i >= 0; i--)
{
if (step[i][d])
{
solution[i] ='U';
d -= distances[i];
}
else
{
solution[i] ='D';
d += distances[i];
}
}
solution[M] = '\0';
}
int main()
{
int distances[MAXM];
int DP[MAXM][MAXD];
// record how did you get here:
// step[i][d] = true means from i - 1 to i, it goes UP
bool step[MAXM][MAXD];
char solution[MAXM];
int N;
scanf("%d", &N);
for (int t = 0; t < N; ++t)
{
int M;
scanf("%d", &M);
int sum = 0;
for (int i = 0; i < M; ++i)
{
scanf("%d", &distances[i]);
sum += distances[i];
}
// initialize DP[][]
for (int i = 0; i < M; ++i)
{
for (int d = 0; d <= sum; ++d)
{
DP[i][d] = sum + 1;
step[i][d] = false;
}
}
// has to go up in the first step
func(0, distances[0], distances[0], true, DP, step, distances, M);
if (DP[M - 1][0] == sum + 1)
{
printf("IMPOSSIBLE\n");
}
else
{
solution[M] = '\0';
buildSolution(solution, step, distances, M);
printf("%s\n", solution);
}
}
return 0;
}