我正在关注一个网站的教程(下面的链接),并从那里我试图实现"最大连续和子数组"的标准问题。但他们在尝试使用样本数组的代码后:{15,-1,-3,4,-5}显示的答案是:" SMCSS值= 4从3开始并以3" 结束,但它应显示最大值为15,因此开始和结束值为1.这里是代码: 错误 和 我应该修改什么? 链接:http://www.8bitavenue.com/2011/11/dynamic-programming-maximum-contiguous-sub-sequence-sum/
#include<iostream>
#include<stdio.h>
//Initialize the first value in (M) and (b)
using namespace std;
int main(){
int M[8],b[8];
int A[] = {15,-1,-3,4,-5};
M[1] = A[1];
b[1] = 1;
//Initialize max as the first element in (M)
//we will keep updating max until we get the
//largest element in (M) which is indeed our
//MCSS value. (k) saves the (j) position of
//the max value (MCSS)
int max = M[1];
int k = 1;
int n = sizeof(A)/sizeof(int);
cout<<n;
//For each sub sequence ending at position (j)
for (int j = 2; j <= n; j++)
{
//M[j-1] + A[j] > A[j] is equivalent to M[j-1] > 0
if (M[j-1] > 0)
{
//Extending the current window at (j-1)
M[j] = M[j-1] + A[j];
b[j] = b[j-1];
}
else
{
//Starting a new window at (j)
M[j] = A[j];
b[j] = j;
}
//Update max and save (j)
if (M[j] > max)
{
max = M[j];
k = j;
}
}
cout<<"MCSS value = "<<max<<"starts at "<<b[k]<<"ends at"<<k;
return 0;
}
答案 0 :(得分:0)
在我深入研究指数之前有两件事:
数组从0
C++
开始编号。所以我假设一切都从M[0] = A[0]; b[0] = 0;
您应该考虑使用std::vector
这是处理数组的C++
方式。
Here是一个有效的解决方案。
答案 1 :(得分:0)
这里有正确的代码
#include<iostream>
#include<stdio.h>
//Initialize the first value in (M) and (b)
using namespace std;
int main()
{
int M[8],b[8];
int A[] = {15,-1,-3,4,-5};
M[0] = A[0];
b[0] = 0;
//Initialize max as the first element in (M)
//we will keep updating max until we get the
//largest element in (M) which is indeed our
//MCSS value. (k) saves the (j) position of
//the max value (MCSS)
int max = M[0];
int k = 0;
int n = sizeof(A)/sizeof(int);
cout<<n<<endl;
//For each sub sequence ending at position (j)
for (int j = 1; j < n; j++)
{
//M[j-1] + A[j] > A[j] is equivalent to M[j-1] > 0
if (M[j-1] > 0)
{
//Extending the current window at (j-1)
M[j] = M[j-1] + A[j];
b[j] = b[j-1];
}
else
{
//Starting a new window at (j)
M[j] = A[j];
b[j] = j;
}
//Update max and save (j)
if (M[j] > max)
{
max = M[j];
k = j;
}
}
cout<<"MCSS value = "<<max<<" starts at "<<b[k]<<" ends at"<<k;
return 0;
}
你应该从0开始索引;