"Backpack" 0-1 backpack with full backpack one-dimensional array implementation

Source: Internet
Author: User

Backpack problem is very classic, "backpack problem Nine" speak very detailed, suggest to take a look.

Here, I want to give 0-1 backpacks and complete backpack compression space after the implementation, that is, as long as a one-dimensional array.

The 0-1 backpack, unlike the complete backpack, is just the same as the order of the inner loop, so the code is basically the same.

I hope I can help you.

0-1 Backpack:

1#include <bits/stdc++.h>2 using namespacestd;3 intf[1001];4 intw[1001]; 5 intv[1001];6 intMain () {7     intN;8     intW;9Cin>>n>>W;Ten      for(inti =1; i<=n;i++){ OneCin>>w[i]>>V[i]; A     } -memset (f,-10000000,sizeof(f)); -      for(inti =1; i<=n;i++){ the          for(intj = w;j>=0; j--){ -F[J] = max (f[j],f[j-w[i]]+v[i]); -         } -     } +     intMax =0; -      for(inti =1; i<=n;i++){ +         if(f[i]>max) { AMax =F[i]; at         } -     } -printf"%d", max); -}


Full backpack:

1#include <bits/stdc++.h>2 using namespacestd;3 intf[1001];4 intw[1001]; 5 intv[1001];6 intMain () {7     intN;8     intW;9Cin>>n>>W;Ten      for(inti =1; i<=n;i++){ OneCin>>w[i]>>V[i]; A     } -memset (f,-10000000,sizeof(f)); -      for(inti =1; i<=n;i++){ the          for(intj =0; j<=w;j++){ -F[J] = max (f[j],f[j-w[i]]+v[i]); -         } -     } +     intMax =0; -      for(inti =1; i<=n;i++){ +         if(f[i]>max) { AMax =F[i]; at         } -     } -printf"%d", max); -}

  

"Backpack" 0-1 backpack with full backpack one-dimensional array implementation

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.