貪心算法 一.部分背包問題


 1 #include<iostream>
 2 #include<string.h>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 //問題表示
 7 int n=5;  
 8 double W=100;    //背包容量
 9 struct nodetype
10 {
11     double w;
12     double v;
13     double p;//p=v/w 單位價值
14     bool operator<(const nodetype &s) const
15     {
16         return p>s.p;  //利用sort將樣例按p遞減排序(類中成員p的比較大小 並返回bool型的值) 
17      } 
18 };
19 nodetype A[]={{0},{30,65},{20,30},{50,60},{10,20},{40,40}};//下標0不用 
20 
21 void dispA()
22 {
23     for(int i=1;i<=n;i++)
24     cout<<A[i].w<<" "<<A[i].v<<" "<<A[i].p<<endl;
25 }
26 
27 //求解結果表示
28 #define maxn 100
29 double V;//最大價值 
30 double x[maxn]; 
31 
32 void knap()//求解背包問題並返回總價值 
33 {
34     V=0;//V初始化為0
35     double weight=W;//背包中能裝入的余下容量 
36     memset(x,0,sizeof(x));
37     int i=1;
38     
39     while(A[i].w<weight)  //物品i能夠全部裝入時循環
40     {
41         x[i]=1;
42         weight-=A[i].w; 
43         V+=A[i].v;
44         i++;
45     } 
46     
47     if(weight>0)//當余下重量大於0 
48     {
49         x[i]=weight/A[i].w;//物品i的一部分裝入
50         V+=x[i]*A[i].v;//累計總價值 
51     }
52 }
53 
54 int main()
55 {
56     cout<<"求解過程:"<<endl;
57     for(int i=1;i<=n;i++)
58     A[i].p=A[i].v/A[i].w;
59     cout<<"排序前:"<<endl;
60     dispA();
61     
62     sort(A+1,A+n+1);  //A[1...n]排序
63      
64     cout<<"排序后:"<<endl;
65     dispA();
66     
67     knap();
68     
69     cout<<"求解結果:";//輸出結果
70     
71     cout<<"  x:[";
72     for(int j=1;j<=n;j++)
73     cout<<x[j]<<" "; 
74     cout<<"]"<<endl;
75     cout<<"總價值="<<V<<endl;
76     return 0; 
77 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM