POJ 3211 Washing Cloths(01背包变形)
Q: 01背包最后返回什么 dp[v], v 是多少?
A: 普通01背包需要遍历, 从大到小. 但此题因为物品的总重量必定大于背包容量, 所以直接返回 dp[V] 即可
update 2014年3月14日11:22:55
1. 几个月后, 感觉返回的不应该是 dp[V], 二是 dp[0...V] 中的最大值
Description
Dearboy was so busy recently that now he has piles of clothes to wash. Luckily, he has a beautiful and hard-working girlfriend to help him. The clothes are in varieties of colors but each piece of them can be seen as of only one color. In order to prevent the clothes from getting dyed in mixed colors, Dearboy and his girlfriend have to finish washing all clothes of one color before going on to those of another color.
From experience Dearboy knows how long each piece of clothes takes one person to wash. Each piece will be washed by either Dearboy or his girlfriend but not both of them. The couple can wash two pieces simultaneously. What is the shortest possible time they need to finish the job?
Input
The input contains several test cases. Each test case begins with a line of two positive integers M and N (M < 10, N < 100), which are the numbers of colors and of clothes. The next line contains M strings which are not longer than 10 characters and do not contain spaces, which the names of the colors. Then follow N lines describing the clothes. Each of these lines contains the time to wash some piece of the clothes (less than 1,000) and its color. Two zeroes follow the last test case.
Output
For each test case output on a separate line the time the couple needs for washing.
Sample Input
3 4 red blue yellow 2 red 3 blue 4 blue 6 red 0 0
Sample Output
10
思路:
1. 先将颜色相同的衣服聚类到一起
2. 对某一种颜色的衣服两人开洗, 这就涉及到01背包的变形, 即如何分配衣服使得总时间最小. 解法是将背包容量设置为总容量的一半, 然后进行01背包
总结:
1. map 和 vector<vector<> > 搭配的不够默契, 与 vector in[MAXN] 比较默契
2. memset 减少时间的方法, memset(dp, 0, sizeof(int)*(V+1));
3. 这里, 因此 V 是 sum/2 后的结果, 所以最终会填满背包, 返回 dp[V] 即可
代码:
#include <iostream> #include <map> #include <vector> #include <string> using namespace std; int M, N; vector<int> cloth[11]; map<string, int> color; int dp[100010]; int solve_dp() { int sum = 0; for(int index = 0; index < M; index++) { int V = 0; for(int j = 0; j < cloth[index].size(); j ++) { V += cloth[index][j]; } int rem = V&1; memset(dp, 0, sizeof(int)*(V+1)); V = V>>1; for(int j = 0; j < cloth[index].size(); j ++) { int wj = cloth[index][j]; for(int k = V; k >= wj; k --) { dp[k] = max(dp[k], dp[k-wj]+wj); } } sum += ((V<<1)+rem)-dp[V]; } return sum; } int main() { freopen("E:\\Copy\\ACM\\测试用例\\in.txt", "r", stdin); while(scanf("%d%d", &M, &N) && M != 0) { string str; color.clear(); for(int i = 0; i < M; i ++) cloth[i].clear(); for(int i = 0; i < M; i ++) { cin >> str; color[str] = i; } int t; for(int i = 0; i < N; i ++) { cin >> t >> str; cloth[color[str]].push_back(t); } cout << solve_dp() << endl; } return 0; }