Greedy thinking: Find the best solution for every step of the problem. Because each step is optimal, the probability of the final optimization is very high.
Part of the idea of the backpack is: the most valuable to the bag, the more loaded the better. Visible design algorithm people are so greedy ah, hey ~
Examples:
n Kinds of things, the weight is MI, the value is VI, the unit price is the ratio of pi. C is the capacity of the small package. The final result is that the corresponding fetch XI is placed in the package.
The code is as follows:
#include <iostream>using namespace std;float *m,*v,*p,*x;float c;//backpack capacity int n,h;void taskinitial (); void Result_ Out (); void Greedy_beibao (); void calculate_p (); int find_next_big_p (int); void Load_beibao (int); int main () {taskinitial (); Greedy_beibao (); Result_out (); return 0;} /* Basic Input Output */void taskinitial () {cin>>c;//Backpack capacity cin>>n;//item Type m= (FLOAT *) malloc (n*sizeof (float));//Storage Item Quality v= ( float *) malloc (n*sizeof (float));//storage items corresponding to the total value p= (float *) malloc (n*sizeof (float));//Storage Item Unit Price x= (float *) malloc (n*sizeof ( float);//The number of items stored in the backpack for (int i=0;i<n;i++) {cin>>* (m+i) >>* (v+i); * (p+i) = (* (v+i))/(* (M+i)); * (x+i) = 0;}} void Result_out () {float totalval=0;for (int i=0;i<n;i++) {cout<<* (x+i) <<endl;totalval+= ((* (V+i))/(* ( m+i))) * (* (x+i));} cout<< "Total value:" <<TOTALVAL<<ENDL;} /* Greedy algorithm */void Greedy_beibao () {H=1;load_beibao (find_next_big_p (h));} int find_next_big_p (int i) {float tempdata;int k=0;for (int j=0;j<n;j++) if (* (P+J) >* (p+k)) k=j;* (p+k) =0;return K;} void Load_beibao (int k) {if (c<=* (M+k)) * (x+k) =c;else{* (x+k) =* (m+k); c-=* (m+k); H++;if (h<=n) Load_beibao (find_next_big_p (h));}}
Test it:
Part of the backpack problem is temporarily fixed, continue!
Partial knapsack algorithm of greedy thought