【发布时间】:2019-06-12 18:25:04
【问题描述】:
我正在尝试学习动态编程,因此我正在尝试解决UVA 11450。因为我知道我可以使用回溯来解决这个问题,所以我决定使用回溯来解决它,然后在代码中添加记忆。但是,我无法做到这一点。
这里是没有记忆的注释代码:
#include <bits/stdc++.h>
using namespace std;
bool b; // this tells us if a solution is found or not
int c; // store input c
vector <vector <int>> arr; // declare a global array to store the type and cost of the garments
int money = INT_MAX; // these two fields store the most optimal solution found so far
vector <int> garr;
// this function fills 'c' - the candidates for the k'th postition
void construct_candidates(vector <int> &a, int k, int m, vector<int> &c)
{
for (int i: arr[k])
{
if (i <= m ) c.push_back(i); // if cost of the model 'i' of garment 'k' is less than or equal to money remaining,
} // put it in array 'c'.
}
void backtrack(vector <int> &a, int k, int m)
{
vector <int> c; // this array stores the candidates for postion k.
if (k == a.size() - 1) // if (is_a_soln) process_solution
{
if (m < money)
{
b = true;
money = m;
garr = a;
}
}
else // else backtrack with updated parameters
{
k++;
construct_candidates(a, k , m, c);
for (int i = 0; i < c.size(); i++)
{
a[k] = c[i];
backtrack(a, k, m - c[i]);
}
}
}
int main()
{
int n;
cin >> n;
while (n--)
{
b = false; // initialising global variables
money = INT_MAX;
arr.clear();
int m;
cin >> m >> c;
arr = vector <vector <int>>(c);
for(int i = 0; i < c; i++) // storing the input in arr
{
int k;
cin >> k;
arr[i] = vector <int> (k);
for (int j = 0; j < k; j++)
{
cin >> arr[i][j];
}
}
vector <int> a(c, -1); // the backtracking code will attempt
//to fill this array with optimal garments
backtrack(a, -1, m);
if (b) cout <<m - money << endl;
else cout << "no solution" << endl;
}
return 0;
}
现在,为了添加记忆,我尝试这样做:
vector <vector <int>> dp(20, vector<int> (201, -1));
void backtrack(vector <int> &a, int k, int m)
{
if (dp[k][m] != -1) // this is
{ // the
k++; // part
a[k] = dp[k][m]; // that
backtrack(a, k, m - a[k]); // is
} // added
else
{
vector <int> c;
if (k == a.size() - 1)
{
if (m < money)
{
b = true;
money = m;
garr = a;
}
}
else
{
k++;
construct_candidates(a, k , m, c);
for (int i = 0; i < c.size(); i++)
{
a[k] = c[i];
backtrack(a, k, m - c[i]);
}
}
}
}
但我不知道在哪里或如何添加实际将最佳服装放置在 DP 表中位置 k 的部分。非常感谢任何帮助。
【问题讨论】:
-
首先,为什么您甚至需要存储最佳的成套服装?这个问题只要求最大成本,所以你只需要存储它。在您的情况下,您使用全局变量来跟踪您看到的最大成本,而不是从函数返回它,因此您需要在 DP 表中跟踪的是您是否已经探索过一个状态。如果你到达一个你已经探索过的状态,你可以立即返回而无需做任何事情,因为你知道从这里开始的任何最佳状态都已经被探索过了。
-
@AlexanderZhang 是的,确实如此。我这样做只是因为我认为知道哪些选择会导致最佳解决方案会很好。
-
@AlexanderZhang 我最初认为您的评论只是说代码中不需要“garr”。但是今天再次阅读时,我意识到它还讲述了如何编写 DP 表。所以,我实现了它并且它有效。感谢您的帮助。
标签: c++ dynamic-programming recursive-backtracking