junior19

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Washing Clothes
Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 9851   Accepted: 3158

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

大致题意:两人洗一堆不同颜色衣服,洗每件衣服需要一定的花费时间,而两人只能同时洗同一种颜色的衣服,求洗完全部衣服花费的最小时间。

题解:按每组颜色分类,将一种颜色的衣服(总花费时间T)尽量平均分成两组,取两组中的大值即为洗完这种颜色衣服的最短时间,所以构造一个T/2容量的背包,用01背包即可解出,依此类推处理其他颜色的衣服。

# include <iostream>
# include <cstdio>
# include <cstring>
using namespace std;
int max(int a, int b){return a>b?a:b;}
int main()
{
    string temp;
    int result, m, n, i, j, k,max_v, num, bag[100000], a[11][102];
    while(scanf("%d%d",&m,&n),n+m)
    {
        result = 0;
        string color[11];
        memset(a, 0, sizeof(a));
        for(i=0; i<m; ++i)
            cin >> color[i];
        for(i=0; i<n; ++i)
        {
            scanf("%d",&num);
            cin >> temp;
            for(j=0; j<m; ++j)
                if(temp == color[j])
                {
                    a[j][i] = num;//这里用二维数组偷懒。
                    a[j][101] += a[j][i];
                }
        }
        for(i=0; i<m; ++i)
        {
            if(!a[i][101])
                continue;
            memset(bag, 0, sizeof(bag));
            max_v = a[i][101] / 2;
            for(j=0; j<n; ++j)
                for(k=max_v; k>=a[i][j]; --k)
                    if(bag[k-a[i][j]] + a[i][j] > bag[k])
                        bag[k] = bag[k-a[i][j]] + a[i][j];
            result += max(a[i][101]-bag[max_v], bag[max_v]);
        }
        printf("%d\n",result);
    }
    return 0;
}


posted on 2017-01-13 00:31  junior19  阅读(149)  评论(0编辑  收藏  举报