HDU1059 (dp)

#include 
#include 
#include 
#include 
#define INIT(x,y) memset(x,y,sizeof(x))
using namespace std;
int c[6];
int val[150], num[150];
int dp[10000][10000];
int main()
{
	int cas = 0;
	while (1) {
		INIT(val, 0); INIT(num, 0); INIT(c, 0);
		int sum = 0;
		for (int i = 0; i < 6; ++i) { scanf_s("%d", &c[i]); sum += c[i] * (i + 1); }
		if (sum == 0) break;
		printf("Collection #%d:\n", ++cas);
		int cnt = 0;
		if (sum % 2 == 0)
		{
			for (int i = 0; i < 6; ++i)
			{
				for (int j = 1; j <= c[i]; j <<= 1) 
				{
					val[cnt] = j * (i + 1);
					num[cnt++] = j;
					c[i] -= j;
				}
				if (c[i] > 0)
				{
					val[cnt] = c[i] * (i + 1);
					num[cnt++] = c[i];
				}
			}
			memset(dp, 0, sizeof(dp));
			for(int i=cnt-1;i>=0;i--)
				for (int j = 0; j <=sum/2; j++)
				{
					if (j - val[i] < 0) dp[i][j] = dp[i + 1][j];
					else   dp[i][j] = max(dp[i + 1][j], dp[i + 1][j - val[i]]);
				}
			if (dp[0][sum / 2] == 0)cout << "Can be divided " << endl << endl;
		}
		else printf("Can't be divided.\n\n");
	}
	return 0;
}

多重背包问题,按位分割,避免tlt,之后跑完全背包问题。

你可能感兴趣的:(HDU1059 (dp))