Code on paper: 01 knapsack Problem of Dynamic planning

Source: Internet
Author: User

Topic:

There are n items and a backpack with a capacity of V. The volume of article I is c[i], the value is v[i]. Solving which items are loaded into the backpack maximizes the sum of the values:
There are 5 items, the size of the backpack is 10, their volume is c[5] = {3,5,2,7,4}; Value is v[5] = {2,4,1,6,5}.

Solution:

The final run result diagram is as follows

Solution Analysis

The main program is as follows

All code: (worker input should pay attention to upper bounds check)

1#include <stdio.h>2 3 Static Const intc[5]={3,5,2,7,4};// Cost4 Static Const intv[5]={2,4,1,6,5};//value5 Static intmem_table[6][ One];//MEM table for dynamic programming6 7 Static intWorkerintAbility,intLen) {8 9     if(ability<=0|| len<=0)Ten         return 0; One     if(mem_table[len][ability]!=-1) A         returnmem_table[len][ability]; -     if(len==1){ -         if(ability>=c[len-1]) themem_table[len][ability]=v[len-1]; -         Else -mem_table[len][ability]=0; -}Else{ +         intYes,no; -         if(ability<c[len-1]) +yes=-1; A         Else atYes=worker (ability-c[len-1],len-1) +v[len-1]; -No=worker (ability,len-1); -mem_table[len][ability]= (yes>no)?Yes:no; -     } -     returnmem_table[len][ability]; -      in } -  to intMain () { +  -     //mem_table init to invalid-1 the     inti,j; *      for(i=0;i<6; i++) $          for(j=0;j< One; j + +)Panax Notoginsengmem_table[i][j]=-1; -  the     //Dump +printf"table:\n"); A      for(i=5;i>0; i--) { theprintf"\ t"); +          for(j=1;j< One; j + +)  -printf"%5d", Mem_table[i][j]); $printf"\ n"); $     } -  -     //Call the worker:) theprintf"result:%d\n", Worker (Ten,5)); - Wuyi     //Dump theprintf"table:\n"); -      for(i=5;i>0; i--) { Wuprintf"\ t"); -          for(j=1;j< One; j + +)  Aboutprintf"%5d", Mem_table[i][j]); $printf"\ n"); -     } -  -}

Code on paper: 01 knapsack Problem of Dynamic planning

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.