#include<iostream> using namespace std; int N;//物体个数 int W;//背包载重 int * weight;//N个物体的重量 int * value;//N个物体的价值 int* * a;//二维数组a[N+1][W+1],其中a[0][]=0,a[][0]=0,a[i][j]表示把前i个物体放入载重j的背包中能获得的最大价值 int * result;//0表示不放入,1表示放入 void input(); int compute(); void output(int getvalue); int max(int n,int m); void destroy(); int main() { input(); output(compute()); destroy(); return 0; } void input() { cout<<"输入物体个数:"; cin>>N; cout<<"输入背包载重:"; cin>>W; weight=new int[N]; cout<<"输入"<<N<<"个物体的重量:"<<endl; for(int i=0;i<N;i++) { cin>>weight[i]; } value=new int[N]; cout<<"输入"<<N<<"个物体的价值:"<<endl; for(int j=0;j<N;j++) { cin>>value[j]; } } int compute()//核心代码 { a=new int*[N+1]; for(int t=0;t<=N;t++) { a[t]=new int[W+1]; } for(int c=0;c<N+1;++c)//初始化a[][]=0 { for(int b=0;b<W+1;++b) { a[c][b]=0; } } for(int y=1;y<=W;++y)//设置a[][] { for(int x=1;x<=N;++x) { if(weight[x-1]>y)//超重,不放 { a[x][y]=a[x-1][y]; } else//没超重,可放可不放 { a[x][y]=max(a[x-1][y],a[x-1][y-weight[x-1]]+value[x-1]); } } } result=new int[N]; for(int l=0;l<N;++l)//初始化为0 { result[l]=0; } int w=W; for(int p=N;p>0;p--)//设置result[] { if(a[p][w]!=a[p-1][w])//第p个物体放入了载重为w的背包中 { result[p-1]=1; w=w-weight[p-1]; } } return a[N][W]; } void output(int getvalue) { cout<<"放入背包的物体重量:"; for(int k=0;k<N;k++) { if(result[k]==1) { cout<<weight[k]<<" "; } } cout<<endl; cout<<"放入背包的总价值:"<<getvalue<<endl; } int max(int n,int m) { return n>m?n:m; } void destroy() { delete[] weight; delete[] value; for(int e=0;e<=N;e++) { delete[] a[e]; } delete[] a; }*/ /*#include<iostream> using namespace std; #include<string> #include<sstream> typedef struct _Node { int data; struct _Node * next; }Node; Node * head,* rear; void Initial(); void Insert(int x); int Del(); void Destroy(); int main() { Initial(); char ch; int x; string str; while(1) { getline(cin,str,'.'); istringstream iss(str); iss>>ch; if(ch=='i') { iss>>x; Insert(x); } else if(ch=='o') { cout<<Del()<<endl; } else { break; } } Destroy(); return 0; } void Initial() { head=rear=new Node; head->data=0; head->next=NULL; } void Insert(int x) { rear->next=new Node; rear=rear->next; rear->data=x; rear->next=NULL; ++(head->data); } int Del() { if(head->data!=0) { if(head->data==1) { rear=head; } Node * save=head->next; head->next=head->next->next; int y=save->data; delete save; --(head->data); return y; } else { cout<<"队列已经空了"<<endl; return 11111111; } } void Destroy() { while(head->next!=NULL) { Node * p=head; head=head->next; delete p; } rear=NULL; }