Classic Backpack problem

Source: Internet
Author: User

knapsack problem I
difficulty level: B; run time limit: 1000ms; run space limit: 51200KB; code length limit: 2000000B
Questions Description

    has a backpack volume of v  and n items, and gives each item a volume. Request from n items, any number of packs into the backpack, so that the remaining space of the backpack is minimal.

input
first row two positive integers  V  and  n, respectively, indicating the volume of the backpack and the number of items to be loaded; the second line includes  n   A positive integer that represents the volume of  n  items, separated by a space between 22.
output
A number that indicates the minimum amount of space remaining in the backpack
input Example
24 6
8 3 12 7 9 7
output Show Example
0
Other instructions
data range : 0<v≤20000,0<n≤30
 

It's too simple, transfer equation: Dp[j]=max (dp[j],dp[j-a[i]]+a[i]);.

1#include <iostream>2#include <cstring>3 using namespacestd; 4 intMain ()5 {  6   intV,n;7Cin>>v>>N; 8   inta[n],dp[v+1]; 9Memset (DP,0,sizeof(DP)); Ten    for(intI=0; i<n;i++)  One   {   ACin>>A[i]; -      for(intj=v;j>=a[i];j--)   -Dp[j]=max (dp[j],dp[j-a[i]]+A[i]);  the   }   -cout<<v-Dp[v];  -}
View Code

Classic Backpack problem

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.