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)