Discription
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
题意
两个人同时洗衣服,每人只能同时洗一件衣服,且只能同时洗颜色相同的衣服,并且只有一种颜色的衣服洗完了才能洗下一种颜色的衣服,求解洗衣服所用的最小时间。
思路
将衣服按照颜色分类,求出洗一种颜色衣服所需要的时间和,以时间和的一般进行0-1背包求解,再用总时间和减去0-1背包求解出的最大值,不断累加和就是最小的洗衣服时间。
AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
#include<map>
using namespace std;
int m,n,vv,ans;
char s[30];
int dp[1000010],num[110],v[11][110];
int main()
{
while(scanf("%d %d",&m,&n)&&m&&n)
{
ans=0;
memset(num,0,sizeof(num));
memset(v,0,sizeof(v));
map<string,int>mp;
for(int i=1;i<=m;i++)
{
scanf("%s",s);
mp[s]=i;//建立字符串和数字意义对应关系,方便操作。
}
for(int i=1;i<=n;i++)
{
scanf("%d %s",&vv,s);
num[mp[s]]++;//同一种颜色,不同衣服的下标
v[mp[s]][num[mp[s]]]=vv;表示某种颜色下的第几件衣服的洗衣时间
}
for(int i=1;i<=m;i++)
{
int sum=0;
for(int j=1;j<=num[i];j++)
sum+=v[i][j];//洗同种衣服所需要的时间和
int sss=sum;
sum/=2;
for(int i=0;i<=sum;i++)
dp[i]=0;
for(int j=1;j<=num[i];j++)
for(int p=sum;p>=v[i][j];p--)
dp[p]=max(dp[p],dp[p-v[i][j]]+v[i][j]);//0-1背包模板
ans+=sss-dp[sum];//累加求和
}
printf("%d\n",ans);
}
return 0;
}