Detachable backpack problem (greedy)

Source: Internet
Author: User

Problem Description: Known n items and a C-weight backpack, item I weight of WI, the benefit of pi. The item can be disassembled when the package is loaded, that is, only part of the item or all or not installed. The maximum weight cannot exceed C.

Maximize the overall benefit.

Algorithm thought: First of all to find the most effective unit weight (that is, Pi except WI max), if the C is greater than WI at this time all loaded (sum + = pi), otherwise (sum + = C*pi). Here we define the structure to store WI, Pi,

Pi/wi, three variables, then the WI/PI from the big to the small sort, in order to load until the backpack full. See the code specifically:

1#include <stdio.h>2#include <stdlib.h>3 structnode4 {5     Doublex, y, z6}s[ About];7 //unit weight from large to small quick sort (ie pi/wi);8 intcmpConst void*a,Const void*b)9 {Ten     structNode *c = (node*) A; One     structNode *d = (node*) b; A     returnD->z > C->z?1:-1; - } - intMain () the { -     intI,n; -     DoubleC; -printf"Enter N:"); +scanf"%d",&n); -printf"input C;"); +scanf"%LF",&c); A      for(i=0; i<n; i++) at     { -scanf"%LF%LF",&s[i].x,&s[i].y); -S[i].z = s[i].y/(s[i].x*1.0); -     } -Qsort (S,n,sizeof(s[0]), CMP); -     Doublesum =0.0; in      for(i=0;; i++) -     { to         if(S[i].x <c) +         { -C-=s[i].x; theSum + =s[i].y; *}Else $         {Panax NotoginsengSum + = s[i].z*C; -              Break; the         } +     } Aprintf"max =%g\n", sum); the     return 0; +}

Detachable backpack problem (greedy)

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.