部分揹包問題-貪心法源碼

#include
#include
//#include
using namespace std;

float Value[100]={0};
float Weight[100]={0};
struct performance
{
int num;
float ratio;
};

performance p[100]={0,-1};
float select[100]={0};

void bubblesort(int);
float Bag(int,float);
//bool cmp(performance,performance);

int main(int argc,char * argv[])
{
int ObjectNum=0;
float 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 Selected array:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
cout<<select[i]<<' ';
}
cout<<endl;
cout<<"The selected objects:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
if(select[i])
cout<<"No."<<i<<' ';
}
cout<<endl;
system("pause");
return 0;
}


float Bag(int objectnum,float capacity)
{
float w=0,v=0;
for(int i=1;i<=objectnum;i++)
{
p[i].num=i;
p[i].ratio=Value[i]/Weight[i];
}
bubblesort(objectnum);
for(int i=1;i<=objectnum;i++)
{
if((w+Weight[p[i].num])<=capacity)
{
w+= Weight[p[i].num],select[p[i].num]=1;
v+= Value[p[i].num];
}
else
{
v+=Value[i]*(capacity-w)/Weight[p[i].num];
select[p[i].num]=(capacity-w)/Weight[p[i].num];
break;
}
}
return v;
}

void bubblesort(int LEN)
{
performance t;
for (int j=1;j
{
for (int i=1;i<=LEN-j;i++)
{
if (p[i].ratio
{
       t=p[i];
       p[i]=p[i+1];
       p[i+1]=t;
}
}
}
}

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