poj 3211 Washing Clothes(01背包问题)

亲爱的男孩最近很忙,堆了很多衣服要洗。每件衣服都有一种颜色,为了防止混色,他们必须先洗完同一种颜色的所有衣服。已知每件衣服的洗涤时间,可以由男孩、女孩中的一人单独洗,也可以同时两人洗两件。求完成所有衣物洗涤所需的最短时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Washing Clothes
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 6490 Accepted: 1828

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

Source

分析:这题稍微的加上一点隐藏,其实就是01背包问题,既可以转化为背包必须装满,也可以转化为装得最多的情况,也就是用01背包来判断一些数,经过组合尽量接近这些数的和/2。。。讲得好挫= =,具体看代码吧!
代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int mm=111;
int g[mm][mm],t[mm],s[mm];
bool f[111111];
char color[mm][22],tmp[22];
int n,m;
int getid(char *s)
{
    for(int i=0;i<m;++i)
        if(strcmp(s,color[i])==0)return i;
    return 0;
}
int main()
{
    int i,j,k,ans;
    while(scanf("%d%d",&m,&n),n+m)
    {
        for(i=0;i<m;++i)scanf("%s",color[i]),t[i]=s[i]=0;
        for(i=0;i<n;++i)
        {
            scanf("%d%s",&k,tmp);
            s[j=getid(tmp)]+=k;
            g[j][t[j]++]=k;
        }
        for(ans=k=0;k<m;++k)
        {
            for(i=0;i<=s[k]/2;++i)f[i]=0;
            f[0]=1;
            for(i=0;i<t[k];++i)
                for(j=s[k]/2-g[k][i];j>=0;--j)
                    if(f[j])f[j+g[k][i]]=1;
            for(i=s[k]/2;i>=0;--i)
                if(f[i])break;
            ans+=s[k]-i;
        }
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值