贪心算法解决部分背包问题 在O(lgn)时间内

来源:互联网 发布:跨境电商erp系统源码 编辑:程序博客网 时间:2024/05/16 03:35
//16.2-6 部分背包问题#include <iostream>using namespace std;struct Object//物品信息结构体{int weight;//物品重量int value;//物品价值float num;//可以装入的物品数量int avl;//物品的单位价值};void swap(Object *p,Object *q)//交换两个元素{Object temp;temp=*p;*p=*q;*q=temp;}int Partition(Object A[],int p,int r)  {        int x=A[r].avl;        int i=p-1;        for(int j=p;j<=r-1;j++)       {           if(A[j].avl>x)           {              i=i+1;             swap(&A[i],&A[j]);            }        }        swap(&A[i+1],&A[r]);        return i+1;  }  void Quick_Sort(Object object[],int i,int j)//根据物品的单位价值对物品进行排序{int q;if(i<j){q=Partition(object,i,j);Quick_Sort(object,i,q-1);Quick_Sort(object,q+1,j);}}void Get_avl(int n,Object object[]){for(int i=0;i<n;++i){object[i].avl=object[i].value/object[i].weight;}}void Greedy_Knapsack(int n,float W,Object object[]){//n是物品数量,W是背包的最大容量float c=W;for(int i=0;i<n;++i){object[i].num=0;if(object[i].weight>c)break;else{object[i].num=1;c-=object[i].weight;}} if(i<=n)//当不能放入整个物品时,选取物品一部分放入           object[i].num=c/object[i].weight;     for(i=0;i<n;i++) {        if(object[i].num>0)        cout<<"重量为: "<<object[i].weight<<" 价值为: "<<object[i].value<<" 的物品放入"<<object[i].num<<" 件"<<endl; }}void main(){float M=16;//背包最大重量Object object[4];object[0].weight=6;object[0].value=12;object[1].weight=7;object[1].value=49;object[2].weight=2;object[2].value=18;object[3].weight=5;object[3].value=25;Get_avl(4,object);Quick_Sort(object,0,3);cout<<"The object has been sorted,and the result is:"<<endl;for(int i=0;i<4;++i){cout<<object[i].value<<" "<<object[i].weight<<endl;}Greedy_Knapsack(4,M,object);}

原创粉丝点击