_ (: From 」∠) _
1 #include <cstdio> 2 #include <iostream> 3 #include <ctime> 4 #include <windows.h> 5 #include <algorithm> 6 #include <fstream> 7 using namespace std; 8 struct object 9 { 10 int no; 11 double weight; 12 double value; 13 double average; 14 }; 15 bool cmp(const object &x, const object &Y) 16 { . 17 return x.average> y.average; // from small to large <, descending to the exhaust> 18 is } . 19 void greedySelector ( int m, int W is, int Solution [], struct Object Object []) { 20 is int I = 0 , V = 0 , J = 0 ; 21 is the while ( Object [I] .Weight < W is) 22 is { 23 is Solution [I] = . 1 ; 24 W is = W is -object[i].weight; 25 V = V + object[i].value; 26 i++; 27 } 28 V = V + (W/object[i].weight)*object[i].value; 29 solution[i] = 1; 30 cout << "The corresponding value of the optimal option is:" << V << endl; 31 /*for( i = 0; i < m; i++) 32 { 33 if(solution[i] == 1) 34 { 35 cout << object[i].no << endl; 36 } 37 }*/ 38 } 39 int main(void) 40 { 41 LARGE_INTEGER nFreq; 42 LARGE_INTEGER nBeginTime; 43 LARGE_INTEGER nEndTime; 44 ofstream fout1; 45 ofstream fout2; 46 srand((unsigned int)time(NULL)); 47 int m,i,j,t; 48 double W; 49 double cost; 50 cout << "Please enter the number of times you want to run the program:"; 51 cin >> t; 52 fout1.open("backpack-object.txt",ios::app); 53 if(!fout1){ 54 cerr<<"Can not open file 'backpack-object.txt' "<<endl; 55 return -1; 56 } 57 fout1.setf(ios_base::fixed,ios_base::floatfield); //防止输出的数字使用科学计数法 58 fout2.open("weight.txt-Backpack " , App :: iOS); 59 IF (! Fout2) { 60 cerr, << " Can Not Open File 'Backpack-weight.txt' " << endl; 61 is return - . 1 ; 62 is } 63 is Fout2 .setf (ios_base :: Fixed , ios_base :: FloatField); // prevent digital output using scientific notation 64 for (J = 0 ; J <T; J ++ ) 65 { 66 COUT << " ------ at The ------------ " <<j + 1 << " TH ----------------- Test " << endl; 67 m = . 1 + RAND ()% 100000 ; // number of articles 68 W is = 10 + RAND ()% 100,000 ; // total weight of the backpack 69 FOUT1 m << << " , " ; 70 Fout2 << ( int ) W is << " , " ; 71 is int Solution [m]; 72 Object Object [m]; 73 is for (I = 0;i < m;i++) 74 { 75 object[i].no = i + 1; 76 object[i].value = 1 + rand()%10000; 77 object[i].weight = 1 + rand()%10000; 78 object[i].average = object[i].value/object[i].weight; 79 } 80 QueryPerformanceFrequency(&nFreq); 81 QueryPerformanceCounter(&nBeginTime); 82 sort(object,object + m,cmp); 83 greedySelector(m,W,solution,object); 84 QueryPerformanceCounter(&nEndTime); 85 cost=(double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart; 86 fout1 << cost << endl; 87 fout2 << cost << endl; 88 cout << "The running time is:" << cost << " s" << endl; 89 } 90 fout1.close(); 91 fout2.close(); 92 cout << endl; 93 cout << "Success!" << endl; 94 return 0; 95 }