Python Implementation 0-1 Backpack

Source: Internet
Author: User

Code:

ImportNumPy as NPC=10#Backpack Capacityw=[2,2,6,5,4]#Item Weightv=[5,3,5,4,6]#Item ValueFlag =[0,0,0,0,0]m=np.zeros ([5,11],int)#The matrix used to hold the 5x11 forJinchRange (c+1):#Initialize first row    if(w[0]<=j): M[0][j]=v[0] flag[0]= 1 forIinchRange (1,5):     forJinchRange (c+1):        if(j<W[i]): M[i][j]=m[i-1][j]Else:            if(m[i-1][j-w[i]]+v[i]>m[i-1][j]): M[i][j]= m[i-1][j-w[i]]+V[i]Else: M[i][j]=m[i-1][j]Print("The maximum value is:", M[len (W)-1][c]) forIinchRange (4,0,-1):    if(m[i][c]>m[i-1][c]): Flag[i]= 1C= C-W[i]Else: Flag[i]=0Print("the items selected are:", end =' ') forIinchRange (len (flag)):if(flag[i]==1):        Print(I,end =' ')

Python Implementation 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.