花了也有一段时间理解背包模板和二进制转化,既然普通法做多重背包容易超时,不妨每个都用二进制优化。二进制优化按照2的次幂分堆,每次处理一堆,但因为用while每次乘2是跑完背包乘的,所以需要再跑一次背包。再有就是学到位运算的乘2,感觉有点收获。
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 100005;
int sum;
int dp[N];
void ZeroOnePack(int cost, int weight)
{
for(int i = sum; i >= cost; i --)
dp[i] = max(dp[i], dp[i - cost] + weight);
}
void CompletePack(int cost, int weight)
{
for(int i = cost; i <= sum; i ++)
dp[i] = max(dp[i], dp[i - cost] + weight);
}
void MulPack(int cost, int weight, int countt)
{
if(cost * countt >= sum) //如果背包能满
{
CompletePack(cost, weight);
return;
}
int i = 1;
while(i < countt)
{
ZeroOnePack(i * cost, i * weight);
countt -= i;
i <<= 1;
}
ZeroOnePack(countt * cost, countt * weight);
}
int main()
{
// freopen("in.txt", "r", stdin);
int a[N], Case = 1;
while(1)
{
sum = 0;
for(int i = 1; i <= 6; i ++)
{
scanf("%d", &a[i]);
sum += (a[i] * i);
}
if(!sum) break;
printf("Collection #%d:\n", Case ++);
if(sum % 2 == 1) printf("Can't be divided.\n\n");
else
{
sum /= 2;
for(int i = 0; i <= sum; i ++) dp[i] = 0;
for(int i = 1; i <= 6; i ++)
{
if(a[i]) MulPack(i, i, a[i]);
}
if(dp[sum] == sum) printf("Can be divided.\n\n");
else printf("Can't be divided.\n\n");
}
}
return 0;
}