HDOJ-1059 Dividing

二进制思想求解把每个价值的物品转化为几个独立的物品,在用01背包问题求解.

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

int dp[120005];
int num[7], k[20005];
int main()
{
   // freopen("in.txt", "r", stdin);
    int cas = 0;
    while(1)
    {
        int s1 = 0, s2 = 0;
        for(int i = 1; i <= 6; i++)
        {
            cin >> num[i];
            s1 += num[i];
            s2 += num[i] * i;
        }
        if(s1 == 0)
           break;
        printf("Collection #%d:\n", ++cas);
        if(s2 % 2 == 1)
        {
            cout << "Can't be divided." << endl << endl;
            continue;
        }
        int h = 0;
        for(int i = 1; i <= 6; i++)
        {
         int j;
         for(j = 1; j <= num[i]; j *= 2)
         {
             k[h++] = j * i;
             num[i] -= j;
         }
         if(num[i])
            k[h++] = num[i] * i;
        }

        memset(dp, 0, sizeof(dp));
        dp[0] = 1;
        for(int i = 0; i < h; i++)
            for(int j = s2; j >= k[i]; j--)
             dp[j] |= dp[j-k[i]];

        if(dp[s2/2])
            cout << "Can be divided." << endl;
        else
            cout << "Can't be divided." << endl;
        cout << endl;
    }
    return 0;
}

你可能感兴趣的:(HDOJ-1059 Dividing)