1. 程式人生 > 其它 >7-13 knapsack problem (10分)

7-13 knapsack problem (10分)

技術標籤:作業TAT

Given items of different weights and values, we need find the most valuable set of items that fit in a knapsack of fixed capacity . More details: there are a knapsack of capacity c > 0 and n items(c<1000,n<100). Each item has weight wi > 0 and value vi > 0. Find the selection of items (δi = 1 if selected, 0 if not) that fit, sum(δiwi )≤ c, and the total value, sum( δivi), is maximized.

Input Specifcation:
There are 2 numbers C and n in the first line,that means the capacity and number of items.There are n lines following the first line,there are two numbers in each line,the ith line numbers mean the (i-1)th weight wi-1 > 0and value vi-1 > 0 .

Output Specifcation:
output a number ,it means the max total value.

Input Example:

15 4
3 5
4 6
5 7
7 12

Output Example:

24
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int W, N, w[100], v[100], dp[10000];
    cin >> W >> N;
    for(int i = 1; i <= N; i++) cin >> w[i] >> v[i];
    memset(dp, 0, sizeof(dp));
    for(int i = 1
; i <= N; i++){ for(int j = W; j >= w[i]; j--){ dp[j] = max(dp[j], dp[j - w[i]] + v[i]); } } cout << dp[W] << endl; return 0; }