[编程之美]买书问题

首先想到的是贪心算法,结果贪心策略在这里行不通- -|

贪心
 1 #include <iostream>
2 using namespace std;
3
4 int books[5];
5 int price=8;
6 int categorys;
7 float consumption=0.0;
8 float onSales5=0.25;
9 float onSales4=0.2;
10 float onSales3=0.1;
11 float onSales2=0.05;
12
13 int LargestCategory(int *arr,int n)
14 {
15 int cnt=0;
16 for(int i=0;i<n;++i)
17 if(arr[i]>0)
18 cnt++;
19 return cnt;
20 }
21
22 int RemainBook(int *arr,int begin,int end)
23 {
24 for(int i=begin;i<end;++i)
25 if(books[i]>0)
26 return i;
27 return end;
28
29 }
30
31 int main()
32 {
33 cout <<"Enter numbers you will buy on each book:";
34 for(int i=0;i<5;++i)
35 cin >>books[i];
36
37 while(RemainBook(books,0,5)!=5)
38 {
39 int idx=0;
40 switch(LargestCategory(books,5))
41 {
42 case 5:
43 for(int i=0;i<5;++i)
44 {
45 idx=RemainBook(books,idx,5);
46 books[idx]--;
47 consumption+=(1-onSales5)*price;
48 }
49 break;
50 case 4:
51 for(int i=0;i<4;++i)
52 {
53 idx=RemainBook(books,idx,5);
54 books[idx]--;
55 consumption+=(1-onSales4)*price;
56 }
57 break;
58 case 3:
59 for(int i=0;i<3;++i)
60 {
61 idx=RemainBook(books,idx,5);
62 books[idx]--;
63 consumption+=(1-onSales3)*price;
64 }
65 break;
66 case 2:
67 for(int i=0;i<2;++i)
68 {
69 idx=RemainBook(books,idx,5);
70 books[idx]--;
71 consumption+=(1-onSales2)*price;
72 }
73 break;
74 case 1:
75 idx=RemainBook(books,idx,5);
76 books[idx]--;
77 consumption+=price;
78 break;
79 }
80 }
81 cout <<consumption;
82
83 return 0;
84 }

 

你可能感兴趣的:(编程之美)