HDU 2844 Coins(多重揹包)

以前做題目光僅僅侷限於 0 1 揹包 和 完全揹包了。


出來一個  個數確定的揹包就不會了。 看了網上的題解。 原來是多重揹包。 也就是說 用完全揹包和 0 1揹包混合求解的題目。


應該是。 對於 vi*a【i】 >= m  那麼就相當於一個完全揹包。 因爲數量可以超過 最大限制。那麼就可以當做無限個使用。


其他的 就需要二進制來優化了。 比如 13  個 2的話。 就用二進制來表示 1 個 2     2個 2   4 個 2  6 個 2    因爲這樣就可以 把 1 2 3 4 5 6 。。。。這些所有的情況都可以表示出來


比如 5  個 2  就是 1個2 + 4個2   6 就是 2個 2+ 4個2  11 就是 1 + 4 + 6.   所以 當做 0 1 揹包來說的話。 最大表示 只能是 13.   並且可以表示所有的情況。


所以就滿足題意。  就把 原來的  m*(∑a【i】) 變成了  m* (∑log(a【i】))。 優化了很多。



#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <fstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <vector>
#include <cmath>
#include <iomanip>
#include <cmath>
typedef long long LL;
typedef unsigned long long LLU;
const double PI=acos(-1.0);
using namespace std;
#define MAXN 100+10
#define INF 1 << 30
struct Coin{
    int v;
    int num;
};
int main (){
    int n,m;
    while(scanf("%d%d",&n,&m) != EOF){
        if(n == 0 && m == 0)
        break;
        Coin s[MAXN];
        int f[100000+10] = {0};
        f[0] = 1;
        for(int i = 1; i <= n; i++)
            scanf("%d",&s[i].v);
        for(int i = 1; i <= n; i++)
            scanf("%d",&s[i].num);
        for(int i = 1; i <= n; i++){
            if(s[i].num*s[i].v >= m){
                for(int j = s[i].v; j <= m; j++)
                    f[j] = f[j]|f[j-s[i].v];
            }
            else{
                int k = s[i].num/2;
                int j;
                for(j = 1; j <= k; j=(j<<1)){
                    for(int x = m; x >= s[i].v*j; x--){
                        f[x] = f[x]|f[x-s[i].v*j];
                    }
                }
                k = s[i].num+1-j;
                for(int x = m; x >= s[i].v*k; x--)
                    f[x] = f[x]|f[x-s[i].v*k];
            }
        }
        int co = 0;
        for(int i = 1; i <= m; i++)
            co += f[i];
        printf("%d\n",co);
    }
    return 0;
}


發佈了141 篇原創文章 · 獲贊 0 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章