01揹包問題-動態規劃源碼

#include
#include
#include
#define max(a,b) (((a) > (b)) ? (a) : (b))
using namespace std;

int M[100][100]={0};
int Value[100]={0};
int Weight[100]={0};
bool Select[100]={0};

int Bag(int,int);
void Selected(int,int);

int main(int argc,char * argv[])
{
int ObjectNum=0;
int Capacity=0;
cout<<"Please input the number of the objects:"<<endl;
cin>>ObjectNum;
cout<<"Please input the value and weight of each object:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
cout<<"Number "<<i<<':'<<endl;
cin>>Value[i]>>Weight[i];
}
cout<<"Please input the capacity:"<<endl;
cin>>Capacity;
cout<<"The result is:"<<endl;
cout<<Bag(ObjectNum,Capacity)<<endl;
cout<<"The Matrix:"<<endl<<"  ";
for(int i=1;i<=ObjectNum;i++)
{
for(int j=1;j<=Capacity;j++)
{
cout<<M[i][j]<<setw(3);
}
cout<<endl;
}
// Selected(ObjectNum,Capacity);
cout<<"Accroading to the Selected matrix(";
for(int i=1;i<=ObjectNum;i++)
{
cout<<Select[i]<<' ';
}
cout<<"),\n the selected objects are:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
if(Select[i])
cout<<"No."<<i<<' ';
}
cout<<endl;
system("pause");
return 0;
}

int Bag(int ObjectNum,int Capacity)
{
for(int i=1;i<=ObjectNum;i++)
{
for(int j=1;j<=Capacity;j++)
{
if(j
{
M[i][j]=M[i-1][j];
}
else
{
M[i][j]=max(M[i-1][j],(M[i-1][j-Weight[i]]+Value[i]));
}
}
}
int c=Capacity;
    for(int i=ObjectNum;i>=1;i--)
    {
if(M[i][c]>M[i-1][c])
        {
        Select[i]=1;
        c=c-Weight[i];
        }
    else
        Select[i]=0;   
    }
return M[ObjectNum][Capacity];
}


void Selected(int ObjectNum,int Capacity)
{
cout<<"The selected objects:"<<endl;
Select[1]=M[1][Capacity]==0? 0:1;
for(int i=ObjectNum;i=1;i--)
{
if(M[i][Capacity]>M[i-1][Capacity])
{
Select[i]=1;
Capacity=Capacity-Weight[i];
}
else
Select[i]=0;
}
}


發佈了36 篇原創文章 · 獲贊 65 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章