下午,所以我正在研究杆切割问题。任何人都知道为什么在将n硬编码为7或main中的其他数字时此代码起作用,但是当我通过std:cin抓取n时,它不起作用并给出所有错误的输出...这是怎么回事? 这是从设置in in main in n = 7中输出的 18岁 1 6 -1 当使用std in获得n = 7时,我得到了: 35 1 1 1 1 1 1 1 -1 -1 两种情况下的价目表都相同。 1个 5 8 9 10 17 17
#include <iostream>
#include <cstring>
using namespace std;
const int A = 1000;
int p[A];
int r[A], s[A];
void init() {
p[0] = 0;
p[1] = 1;
p[2] = 5;
p[3] = 8;
p[4] = 9;
p[5] = 10;
p[6] = 17;
p[7] = 17;
p[8] = 20;
p[9] = 24;
p[10] = 30;
}
int extendedButtomUpCutRod(int n) {
for (int j = 1; j <= n; ++j) {
int q = -2145631872;
for (int i = 1; i <= j; ++i)
if (q < p[i] + r[j - i]) {
q = p[i] + r[j - i];
s[j] = i;
}
r[j] = q;
}
return r[n];
}
// prins the extended method's output
void printCutRodSoln(int n) {
do
cout << s[n] << " ";
while ((n -= s[n]) > 0);
}
int main(){
init();
r[0] = 0;
//int n = 7; //works when this is used.
int n;
std::cin >> n; //doesnt work when this is used?
for(int i = 0; i <= n; i++){
std::cin >> p[i];
}
cout << extendedButtomUpCutRod(n) << endl;
printCutRodSoln(n);
std::cout << "-1"<< std::endl;
}
答案 0 :(得分:0)
评论有所帮助,但这是确切的界线。需要改变... for(int i = 1; i <= n; i ++), i = 1在所有测试案例中均已解决。 价格表已关闭。