演算法練習題——0 1背包問題__演算法

來源:互聯網
上載者:User

時間限制:  2  S         記憶體限制:  128  MB 題目描述:

 給你一個固定容量的背包v,和n個物品。每個物品有它的體積和價值,每個物品只能拿1個,在總物品的體積不超過背包容量的前提下可以獲得的最大價值。 
 輸入: 
 第一行輸入兩個int型整數v和n,表示背包的容量和給出的物品數。(v<=1000,n<=100)然後給出n個物品,vi和mi表示物品的體積和價值。(1<=vi<=mi<=1000) 
 輸出: 
 輸出一個整數表示所能得到的最大價值並換行。 
 範例輸入: 
 100 5 77 92 22 22 29 87 50 46 99 90 
 範例輸出: 
 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>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;
}  



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.