NYOJ 860 又見01背包

來源:互聯網
上載者:User

標籤:

 

 有n個重量和價值分別為wi 和 vi 的 物品,從這些物品中選擇總重量不超過 W 的物品,求所有挑選方案中物品價值總和的最大值。  1 <= n <=100  1 <= wi <= 10^7  1 <= vi <= 100  1 <= W <= 10^9
輸入
多組測試資料。
每組測試資料第一行輸入,n 和 W ,接下來有n行,每行輸入兩個數,代表第i個物品的wi 和 vi。
輸出
滿足題意的最大價值,每組測試資料佔一行。
範例輸入
4 52 31 23 42 2
範例輸出
7
思路:由於重量太大不可能開重量的數組,所以我們可以這樣考慮,求當前價值下的最小重量,這樣的話問題就簡單解決了;
 1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 using namespace std; 6 const int MAX = 0x3fffffff; 7 const int N = 1e4+10; 8 struct T 9 {10     int wi,vi;11 }ma[110];12 long long dp[N];13 int main()14 {15     int n , W, M;16     while(scanf("%d %d",&n,&W) !=EOF)17     {18         M = 0;19        fill(dp,dp+N,MAX);20         for(int i = 1;i<=n ; i++)21         {22             scanf("%d%d",&ma[i].wi,&ma[i].vi);23             M = ma[i].vi + M;24         }25         dp[0] = 0;26         //常用的01背包27        for(int i = 1; i<=n; i++)28           for(int j = M; j>=ma[i].vi; j--)29           {30             dp[j] = min(dp[j],dp[j-ma[i].vi]+ma[i].wi);31           }32           int ans = 0;33           for(int i = M; i>=0; i--)34           {35               if(dp[i]<=W) {ans = i;break;}//從最大的價值開始遍曆,最大價值不會超過1w36           }37           printf("%d\n",ans);38     }39     return 0;40 }

 

NYOJ 860 又見01背包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.