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 integers M and N (M < 10, N < 100), which are the numbers of colors and of clothes. The next line contains Mstrings 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.
For each test case output on a separate line the time the couple needs for washing.
3 4 red blue yellow 2 red 3 blue 4 blue 6 red 0 0Sample Output
10
题意:两个人洗衣服, 每种颜色的衣服有多件, 要求两人只能同时洗相同颜色的衣服, 求洗衣服的最短时间。
分析:因为只能同时洗相同颜色的衣服, 因此可将不同颜色的衣服看为不同的组, 分别求出来每组的最短时间, 其和即为所求;每组最短时间就是0 1背包;对于每种颜色洗它都有一个总时间,要求洗这种颜色的最少时间,就是求看能不能一个人洗这种颜色的衣服达到总时间的一半,也就是让两个人洗这种颜色的衣服的时间尽可能相同。
解题思路:先求出洗每种颜色的衣服所用的总时间,为了让两个人所用时间尽可能相同,把总时间的一半当做背包容量,每件衣服所花费的时间既是物体体积,又是物品价值,这样就转化为01背包,求背包的最大价值,然后用这种颜色的总时间减去最大价值就是洗这种颜色的衣服所用的最短时间。
代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
vector<vector<int> > a(15);
int num[12];
int dp[1000010];//??!!//以后大方点
//int zeroonepaket(int k,int m) //尽量少用函数,超时。。
//{
// memset(dp,0,sizeof(dp));
// int n=a[k].size();
// for(int i=0;i<n;i++)
// {
// for(int j=m;j>=a[k][i];j--)
// {
// dp[j]=max(dp[j],dp[j-a[k][i]]+a[k][i]);
// }
// }
// return dp[m];
//}
int main(void)
{
int m, n;
ios::sync_with_stdio(false);
while(cin>>n>>m)
{
if(n==0&&m==0)
break;
map<string,int> mp;
string colors;
for(int i=1; i<=n; i++)
{
cin>>colors;
mp[colors]=i;
num[i]=0;
a[i].clear();
}
int number;
for(int i=1; i<=m; i++)
{
cin>>number>>colors;
int c=mp[colors];
a[c].push_back(number);
num[c]+=number;
}
int sum=0;
for(int h=1; h<=n; h++)
{
memset(dp,0,sizeof(dp));
int na=a[h].size();
int ma=num[h]/2;
for(int i=0;i<na;i++)
{
for(int j=ma;j>=a[h][i];j--)
{
dp[j]=max(dp[j],dp[j-a[h][i]]+a[h][i]);
}
}
sum+=(num[h]-dp[ma]);
}
cout<<sum<<endl;
}
return 0;
}