Washing Clothes
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
Sample Output 10 |
题意:给定各种颜色衣服,每个衣服时间给定,夫妇两人每次只能洗同一种颜色的衣服,问最少需要多少时间。
解题思路:对于每种颜色,时间最少则是要充分利用两个人,即两人洗衣服时间尽量相同。对于每一种颜色,可以用01背包求的dp[sum/2]的值,即sum/2时间内能洗的最多时间,sum是总时时间。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char col[100];
struct clothes {
int num; // 衣服数量
int sum; // 总时间
char color[100];
int time[120]; // 对应需要的时间
}type[12];
int dp[500000];
int main()
{
int m, n, times;
while(~scanf("%d%d", &m, &n) && (m+n)) {
for(int i = 0; i < m; i++) {
scanf("%s", &type[i].color);
type[i].num = 0;
type[i].sum = 0;
}
for(int i = 0; i < n; i++) {
scanf("%d%s", ×, &col);
for(int j = 0; j < m; j++) {
if(strcmp(col, type[j].color) == 0) {
int temp = type[j].num;
type[j].time[temp] = times;
type[j].num++;
type[j].sum += times;
break;
}
}
}
int ans = 0;
for(int i = 0; i < m; i++) {
memset(dp, 0, sizeof(dp)); // 初始化,每次都是求每一种颜色的最短时间
// 01背包
for(int j = 0; j < type[i].num; j++) {
for(int k = type[i].sum/2; k >= type[i].time[j]; k--) {
dp[k] = max(dp[k], dp[k-type[i].time[j]]+type[i].time[j]);
}
}
ans += type[i].sum - dp[type[i].sum/2];
}
printf("%d\n", ans);
}
return 0;
}