0/1 Backpack

Source: Internet
Author: User

1  ProgramPackage ;2 Const 3maxm= $; maxn= -;4 var 5   M,n,j,i:integer;6C,w:Array[1.. MAXN] ofinteger;7F:Array[0.. MAXN,0.. MAXM] ofinteger;8 functionMax (X,y:integer): integer; //to find the maximum value of x and Y9 beginTen   ifX>y ThenMax:=xElsemax:=y; One End; A 
- BEGIN -Assign (input,'package.in'); theAssign (output,'Package.out'); - reset (input); - rewrite (output); -READLN (M,n); //backpack capacity m and number of items n + fori:=1 toN Do -READLN (W[i],c[i]); //weight and value of each item + fori:=1 toN Do A forj:=1 toM Do at begin//f (i,x) denotes the top I item, the total weight does not exceed the optimal value of x - ifJ>=w[i] ThenF[i,j]:=max (f[i-1, j-w[i]]+c[i],f[i-1, J]) - Elsef[i,j]:=f[i-1, j]; - End; -Writeln (F[n,m]); //F (n,m) is the optimal solution - close (input); in close (output); -END.

It is convenient to use a two-dimensional array to store each sub-problem, but when the MAXM is large, you cannot define a two-dimensional array F, but you can actually use a one-dimensional array.

1  ProgramStar_package;2 var3     I,j,k,n,m:longint;4F:Array[0..100000] ofLongint;5W,c:Array[0.. -] ofLongint;6 begin7Assign (input,'package.in');8Assign (output,'Package.out'); 9 reset (input);Ten   rewrite (output); OneFillchar (F,sizeof (f),0); AREADLN (M,n); //backpack capacity m and number of items n -    fori:=1  toN Do  -READLN (W[i],c[i]); //weight and value of each item the    fori:=1  toN Do -      forJ:=mDowntoW[i] DoThis cannot be written for J:=w[i] tom -       ifF[J-W[I]]+C[I]>F[J] ThenF[j]:=f[j-w[i]]+c[i]; //F (j) means the maximum value of the weight not exceeding J kg - Writeln (f[m]); + close (input); -   Close (ouptut); + End.

0/1 Backpack

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.