Washing Clothes - POJ 3211 01背包

来源:互联网 发布:中国电信云计算干嘛的 编辑:程序博客网 时间:2024/05/22 15:33

Washing Clothes
Time Limit: 1000MS Memory Limit: 131072KTotal Submissions: 8563 Accepted: 2680

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

题意:两个人只能同时洗一样颜色的衣服,洗完一种颜色的衣服才能洗下一种颜色的衣服。

思路:颜色之间可以分组再求和,先讨论一种颜色。将一种颜色的时间求和sum,sum/2当做是背包容量,sum减去它能装的最大时间,就是洗这种颜色的衣服需要的最短时间。

AC代码如下;

#include<cstdio>#include<cstring>#include<map>#include<string>using namespace std;map<string,int> match;char s[20];int tim[20][110],dp[100010];int main(){ int n,m,i,j,k,num,sum,ans;  while(~scanf("%d%d",&m,&n) && n>0)  { ans=0;    match.clear();    memset(tim,0,sizeof(tim));    for(i=1;i<=m;i++)    { scanf("%s",s);      match[s]=i;    }    for(i=1;i<=n;i++)    { scanf("%d%s",&num,s);      k=match[s];      tim[k][0]++;      tim[k][tim[k][0]]=num*2;    }    for(i=1;i<=m;i++)    { memset(dp,0,sizeof(dp));      sum=0;      for(j=1;j<=tim[i][0];j++)       sum+=tim[i][j];      sum/=2;      for(j=1;j<=tim[i][0];j++)       for(k=sum;k>=tim[i][j];k--)        dp[k]=max(dp[k],dp[k-tim[i][j]]+tim[i][j]);      ans+=sum*2-dp[sum];    }    printf("%d\n",ans/2);  }}




0 0
原创粉丝点击