poj3211Washing Clothes(分成多组01背包) .......经典

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=两人用时最少洗完这同一颜色的衣服。
#include<stdio.h>
#include<string.h>
struct node
{
    int k,sum;//这种颜色的件数和总时间
    int time[105];//每件衣的用时
}c[15];//同一类的衣服
int main()
{
    int n,m,tim,dp[100005];
    char color[15][50],col[50];
    while(scanf("%d%d",&n,&m)>0&&n+m!=0)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%s",color[i]);
            c[i].k=0; c[i].sum=0;
        }
        for(int i=1;i<=m;i++)
        {
            scanf("%d%s",&tim,col);
            for(int j=1;j<=n;j++)
            if(strcmp(col,color[j])==0)
            {
                c[j].k++; c[j].sum+=tim;
                c[j].time[c[j].k]=tim;
            }
        }
        tim=0;
        for(int i=1;i<=n;i++)
        if(c[i].k)
        {
            memset(dp,0,sizeof(dp));
            int hlf=c[i].sum/2;
            for(int e=1;e<=c[i].k;e++)//第i种颜色的衣服第e件
            {
                int use=c[i].time[e];
                for(int u=hlf;u>=use;u--)//01背包
                if(dp[u]<dp[u-use]+use)
                dp[u]=dp[u-use]+use;
            }
            tim+=(c[i].sum-dp[hlf]);
        }
        printf("%d\n",tim);
    }
}


你可能感兴趣的:(背包)