【发布时间】:2014-08-29 22:50:36
【问题描述】:
让我们有一个(给定尺寸的)小方块的字段,每个方块都有一个值。从每个方格,一个人只能移动到正下方的方格,或者对角线向左或向右的那个方格。任务是找到穿越该领域的最大组合价值。
例如对于输入
1
6 5
3 1 7 4 2
2 1 3 1 1
1 2 2 1 8
2 2 1 5 3
2 1 4 4 4
5 2 7 5 1
输出应该是 32,但我的代码输出 20。
我的方法是通过以下方式详尽地尝试通过该领域的所有可能路线:
y == last_row return value[x,y]
f(x,y)
y != last_row return value[x,y] + max(f(x-1,y+1),f(x,y+1),f(x+1,y+1))
我的方法、我的代码或两者都有错误吗?
代码在这里:
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
typedef int T;
T max(T x, T y, T z) {
if(x < y) {
if(y < z) return z;
else return y;
}
else {
if(y > z) return x;
else {
if(x > z) return x;
else return z;
}
}
}
//Finds the maximum amount of stones possibly gathered by following coordinates x,y
//The topmost left is (0,0), bottom right is (columns-1,rows-1)
T max_stones_found_following(T x, T y, vector< vector<T> > A) {
//Reached the last row?
if(y == A.size()-1) return A[x][y];
else {
T went_left, went_right, went_down;
if(x-1 >= 0) went_left = max_stones_found_following(x-1, y+1, A);
else went_left = numeric_limits<T>::min();
if(x+1 <= A[x].size()-1) went_right = max_stones_found_following(x+1, y+1, A);
else went_right = numeric_limits<T>::min();
went_down = max_stones_found_following(x, y+1, A);
return A[x][y] + max(went_left, went_right, went_down);
}
}
int main() {
//Initialization
T test_cases, rows, columns, stones_found, max_stones;
vector< vector<T> > A;
cin >> test_cases;
while(test_cases--) {
//Field input
cin >> rows >> columns;
for(int i = 0; i < rows; i++) {
vector<T> row;
for(int j = 0; j < columns; j++) {
T in;
cin >> in;
row.push_back(in);
}
A.push_back(row);
}
max_stones = 0;
stones_found = 0;
//Try starting at different positions in the first row
for(int i = 0; i < columns; i++) {
stones_found = max_stones_found_following(i, 0, A);
if(stones_found > max_stones) max_stones = stones_found;
}
//Output
cout << max_stones << endl;
}
return 0;
}
【问题讨论】:
-
您的解决方案似乎没有使用动态规划。
-
这个练习的“动态”部分在哪里?我看到一个 typedef
T并且没有任何模板(除了使用向量的向量)。告诉你的导师他们对“动态”的定义......不是。 -
@WhozCraig:“动态编程”是系统工程中的一个主题,与动态类型或动态内存管理无关。我绝对不会使用
vector<int>以外的模板来解决这个问题。 -
@BenVoigt 那么不同的思想和感知流派,同意了。除非得到指示,否则我也不会这样做(这里很可能就是这种情况,但很难说)。
标签: c++ algorithm dynamic-programming