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
思路:
对每一种颜色的时间做01 背包。
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
map<string, int> ma;
vector<int> v[15];
int sum[15], dp[100005];
int main()
{
//freopen("in", "r", stdin);
int n, m, a;
string s;
while(~scanf("%d %d", &n, &m)){
if(n == 0 && m == 0) break;
memset(sum, 0, sizeof(sum));
ma.clear();
for(int i = 0; i < n; ++i){
v[i].clear();
}
for(int i = 0; i < n; ++i){
cin>>s;
ma[s] = i;
}
for(int i = 0; i < m; ++i){
cin>>a>>s;
v[ma[s]].push_back(a);
sum[ma[s]] += a;
}
for(int i = 0; i < n; ++i){
sort(v[i].begin(), v[i].end());
}
int ans = 0;
for(int i = 0; i < n; ++i){
//printf("%d\n", sum[i]);
memset(dp, 0, sizeof(dp));
int ss = sum[i]/2;
for(int j = 0; j < v[i].size(); ++j){
for(int k = ss; k >= v[i][j]; --k){
dp[k] = max(dp[k], dp[k - v[i][j]] + v[i][j]);
}
}
ans += max(dp[ss], sum[i] - dp[ss]);
}
printf("%d\n", ans);
}
return 0;
}