poj 3211 Washing Clothes(01背包)

来源:互联网 发布:如何不备案用域名访问 编辑:程序博客网 时间:2024/05/22 16:41

两个人同一时刻只能洗同一颜色的衣服,所以可以按颜色进行分组计算,最后求和。


洗完同一颜色的总时间是固定的,所以两个人洗的时间最短是要让这两个人洗这种颜色的

衣服尽可能接近,因此可以把总时间的一半作为背包容量,然后求01背包,洗这种颜色

衣服的最短时间即为总时间减去背包的最大价值.



代码:

#include<iostream>#include<cstdio>#include<map>#include<cstring>#include<algorithm>using namespace std;const int maxn = 105;int num[15], dp[100005];struct node{    int sum, t[maxn];}a[15];int main(void){    int n, m;    while(cin >> n >> m, n+m)    {        memset(a, 0, sizeof(a));        memset(num, 0, sizeof(num));        int k = 0;        string str;        map<string, int> id;        for(int i = 0; i < n; i++)            cin >> str, id[str] = k++;        for(int i = 0; i < m; i++)        {            int t;            cin >> t >> str;            a[id[str]].sum += t;            a[id[str]].t[num[id[str]]++] = t;        }        int ans = 0;        for(int i = 0; i < n; i++)        {            memset(dp, 0, sizeof(dp));            int M = a[i].sum/2;            for(int j = 0; j < num[i]; j++)                for(int k = M; k >= a[i].t[j]; k--)                    dp[k] = max(dp[k], dp[k-a[i].t[j]]+a[i].t[j]);            ans += a[i].sum-dp[M];        }        printf("%d\n", ans);    }    return 0;}


Washing Clothes
Time Limit: 1000MS Memory Limit: 131072KTotal Submissions: 9784 Accepted: 3134

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 4red blue yellow2 red3 blue4 blue6 red0 0

Sample Output

10

Source

POJ Monthly--2007.04.01, dearboy

1 1