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
#include <iostream> #include <algorithm> #include <queue> #include <stdio.h> #include <string.h> using namespace std; #define MOD 1000000007 #define maxn 100010 char str[20][20]; int dp[maxn]; char ch[20];//记录衣服颜色 int num[20]; int sum[20]; int t; int M,N; int ar[20][100]; int fun()//将各种颜色的衣服分类 { for(int i=1;i<=M;i++) if(strcmp(ch,str[i])==0) return i; return 0; } int main() { while( cin>>M>>N&&N!=0&&M!=0){ int i,j,k; for(i=1;i<=M;i++) { cin>>str[i]; num[i]=sum[i]; } for(i=1;i<=N;i++)//共有N件衣服 { cin>>t>>ch; k=fun(); sum[k]+=t; ar[k][num[k]++]=t; } int L,ans=0; for(i=1;i<=M;i++)//M种颜色,对每一种颜色 { L=sum[i]/2;//sum[i]为洗第i种颜色的衣服所需要的总时间, for(j=0;j<=L;j++) dp[j]=0; // for(j=0;j<num[i];j++)//0-1背包问题,num[i]为第i种颜色的衣服的数量 for(k=L;k>=ar[i][j];k--)//L作为背包容量,选取哪些衣服可使背包中装的物品重量最大(即最接近sum的一半) dp[k]=max(dp[k],dp[k-ar[i][j]]+ar[i][j]); ans+=max(sum[i]-dp[L],dp[L]); } cout<<ans<<endl; } return 0; }