Partial knapsack algorithm of greedy thought

Source: Internet
Author: User

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:" &LT;&LT;TOTALVAL&LT;&LT;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.