Algorithm exercises--0 1 knapsack problem __ algorithm

Source: Internet
Author: User
Tags time limit

Time limit: 2 S Memory limit: 128 MB topic Description:

Give you a fixed capacity of the Backpack V, and n items. Each item has its size and value, each item can only take 1, the total volume of goods does not exceed the capacity of the backpack can be the maximum value. Input:
The first line enters two int-type integers v and N, representing the capacity of the backpack and the number of items given. (v<=1000,n<=100) then give n items, vi and MI to indicate the volume and value of the item. (1<=vi<=mi<=1000) Output:
Outputs an integer representing the maximum value that can be obtained and wraps the line. Sample Input:
100 5 77 92 22 22 29 87 50 46 99-90 Sample output:
133

language:c++

#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>


typedef struct ITEM
{
int VI;
int mi;
}item;
using namespace Std;


int max (int x,int y) {
int temp = 0;
if (x>y) temp=x;
else temp=y;
return temp;


}
int main ()
{
int V;
int n;
cin>>v>>n;
vector<vector<int> > K (v+1,vector<int> (n+1));
Item items[100];
for (int i=0;i<n;i++) {
cin>>items[i].vi;
cin>>items[i].mi;
}
for (int w=0;w<=v;w++)
{
for (int j=0;j<=n;j++)
{
k[w][j]=0;
}

}
for (int w1 = 1;w1<=v;w1++)
{
for (int j=1;j<=n;j++)
{
if (ITEMS[J-1].VI&GT;W1)
{
K[W1][J]=K[W1][J-1];
}
Else
{
K[w1][j]=max (K[w1][j-1], (K[W1-ITEMS[J-1].VI][J-1]+ITEMS[J-1].MI));
}

}

}
cout<<k[v][n]<<endl;
return 0;
}



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.