poj3624 Simple 01 Knapsack problem

Source: Internet
Author: User

Problem Description:

There are a total of N gems to choose from, the weight of gem I is WI, the attraction is Di, can only be used once. Bessie the maximum weight of a gemstone bracelet is M. Give the N,m,wi,di, beg M.

A very standard 01 knapsack problem. Code that uses an optimized one-dimensional array. Because for this kind of problem, only I-1 's f[v] is useful for calculating the f[v of I, so using a one-dimensional array is equivalent to overwriting the previous record before i-1.

Below is my code:

#include <iostream>#include<string.h>#include<stdio.h>#defineM 12880+10using namespacestd;intF[m];intw[3500],d[3500];intMain () {intn,m; scanf ("%d%d",&n,&m); Memset (F,0,sizeof(f));  for(intI=0; i<n;i++) {scanf ("%d%d", w+i,d+i); }     for(intI=0; i<n;i++){         for(intj=m;j>=w[i];j--){            if(f[j]<f[j-w[i]]+D[i]) {F[j]=f[j-w[i]]+D[i]; }}} printf ("%d\n", F[m]); return 0;}

The time complexity of the algorithm is O (MN), and the space complexity is O (M);

poj3624 Simple 01 Knapsack 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.