"Template" 0-1 backpack

Source: Internet
Author: User

0-1 Backpack The essence of the problem is that each item in a sequence has a selection and no two cases
For example, to select several items from a pile of objects to meet certain nature problems
Initialization needs to be noted that at the beginning, the DP array needs to be set to a solution that is not possible relative to the positive solution , which may be 0 or negative infinity, positive infinity, and specific analysis.
Stage: Before processing finished I item
Additional status: What is the current backpack volume?
Different state transfer equations of different problems
The code is as follows:

#include <bits/stdc++.h>using namespace std;const int maxn=1010;int t,m,cost[101],val[101];//m种物品,重量不超过tint dp[maxn];void read_and_parse(){    scanf("%d%d",&t,&m);    for(int i=1;i<=m;i++)scanf("%d%d",&cost[i],&val[i]);    memset(dp,0xcf,sizeof(dp));    dp[0]=0;}void solve(){    for(int i=1;i<=m;i++)        for(int j=t;j>=cost[i];j--)            dp[j]=max(dp[j],dp[j-cost[i]]+val[i]);    int ans=0;    for(int i=0;i<=t;i++)ans=max(ans,dp[i]);    printf("%d\n",ans);}int main(){    read_and_parse();    solve();    return 0;}

"Template" 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.