Washing Clothes poj 3211(01背包)

来源:互联网 发布:婚礼入场音乐知乎 编辑:程序博客网 时间:2024/05/01 18:44

问题描述

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?


输入

The input contains several test cases. Each test case begins with a line of two positive integersM and N (M < 10, N < 100), which are the numbers of colors and of clothes. The next line containsM strings which are not longer than 10 characters and do not contain spaces, which the names of the colors. Then followN 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.


输出

For each test case output on a separate line the time the couple needs for washing.


样例输入

3 4red blue yellow2 red3 blue4 blue6 red0 0

样例输出

10

这题和hdu 1171有点类似。

题目大意是两个人洗衣服,必须同时洗同一种颜色的衣服,这种颜色的衣服洗完才能洗下一种颜色。每一种 颜色的衣服两个人同时洗的话,洗完的最少时间就是两个人最后洗完衣服的那个人的时间,要使这个时间最小,不妨设sum=洗完所有衣服所用的时间;然后找到其中一个人小于sum/2,但最接近sum/2的时间,这样最后洗完的那个人的时间才最小。

#include <iostream>#include <cstdio>#include <cstring>#include <map>using namespace std;int dp[50005];int num[1001];int v[11][101];//v[i][j]表示第i种颜色中的第j件衣服的时间int main(){    int m,n;    while(scanf("%d%d",&m,&n),m&&n)    {                memset(num,0,sizeof(num));        memset(v,0,sizeof(v));        map<string,int> ma;        for(int i=1;i<=m;i++)        {            char a[22];            scanf("%s",&a);            ma[a]=i;        }        for(int i=1;i<=n;i++)        {            char a[22];int k;            scanf("%d",&k);            scanf("%s",&a);            num[ma[a]]++;            v[ma[a]][num[ma[a]]]=k;        }        int ans=0;        for(int i=1;i<=m;i++)            {                               int sum=0;                for(int j=1;j<=num[i];j++)                    sum+=v[i][j];                int sa=sum;                sum/=2;                for(int j=1;j<=sum;j++)                    dp[j]=0;                                for(int j=1;j<=num[i];j++)                for(int k=sum;k>=v[i][j];k--)                    dp[k]=max(dp[k],dp[k-v[i][j]]+v[i][j]);                ans+=sa-dp[sum];            }            printf("%d\n",ans);    }}



0 0
原创粉丝点击