#include<iostream>
#include<string>
using namespace std;
int Max(int x,int y){
int temp;
if(x>y)
temp=x;
else
temp=y;
return temp;
}
int main()
{
int i,j;
int n;
cout<<"输入重量数组大小n:";
cin>>n;
int *w=new int[n];//创建存放重量的一维数组
for(i=0;i<n;i++)
{
cout<<"w["<<i<<"]:";
cin>>*(w+i);//L[i];
}
cout<<"---------"<<endl;
for(i=0;i<n;i++)
{
cout<<"w["<<i<<"]:"<<*(w+i)<<" ";
}
//------------------------------------------
//int m;
//cout<<endl<<"输入价值数组大小m:";
//cin>>m;
int *v=new int[n];//创建存放价值的一维数组
for(i=0;i<n;i++)
{
cout<<endl<<"v["<<i<<"]:";
cin>>*(v+i);//L[i];
}
cout<<"---------"<<endl;
for(i=0;i<n;i++)
{
cout<<"v["<<i<<"]:"<<*(v+i)<<" ";
}
//--------------------------------------------
int W;//背包限重
cout<<endl<<"输入背包限重大小W:";
cin>>W;
int **best= new int*[n];///n行
for(i=0;i<n;i++)
{
best[i]=new int[W];//W列
}
for(i=0;i<n;i++)//开始赋值
{
for(j=0;j<=W;j++)
{
best[i][j]=0;
//cout<<"请输入best["<<i<<"]["<<j<<"]的值:"<<endl;
//cin>>best[i][j];
}
}
for(i=0;i<n;i++)//读取数组best
{
for(j=0;j<=W;j++)
{
cout<<"best["<<i<<"]["<<j<<"]的值为:"<<best[i][j]<<" ";
}
cout<<endl;
}
//------------------------------------------------//为什么只运行到这?下面2部分for循环是没运行吗?
for(i=0;i<n;i++){
for(j=0;j<=W;j++){
if(w[i]>W)
best[i][j]=best[i-1][j];
else
best[i][j]=Max(best[i-1][j],best[i-1][j-w[i]]+v[i]);
}
}
//-------------------------------------
for(i=0;i<n;i++)//读取数组best
{
for(j=0;j<=W;j++)
{
cout<<"best["<<i<<"]["<<j<<"]的值为:"<<best[i][j]<<" ";
}
cout<<endl;
}
//--------------------------内存删除操作;
for(i=0;i<n;i++)
{
delete[] best[i];
}
delete[] best;
delete []w;
delete []v;
return 0;
}
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/401698744336180.png "=600 #left")
请问代码后面一部分为什么运行不出来,整个代码感觉只运行了一半?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- CSDN专家-link 2021-10-06 04:58关注
for(j=0;j<w;j++)
不能j<=w;当j=w时,数组越界了本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
- ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
- ¥15 cmd cl 0x000007b
- ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
- ¥500 火焰左右视图、视差(基于双目相机)
- ¥100 set_link_state
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败
- ¥100 支付宝网页转账系统不识别账号