标签:背包dp
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
这道题是分组背包的变形,先用map把每一个字符串对应每个数字,然后把相同的字符串归为一类,求出最小的时间,然后累加就行了,这里每一组的最短时间可以用01背包,因为是两人同时做,可以知道两人的工作量相差最小时,结束这种颜色的衣服所用的时间最少,所以可以设背包容量为sum[i]/2,然后求这个容量下的最打容量,然后这组所加的时间就是sum[i]-dp[sum[i]/2].这里还要注意一点,初始化的时候不能初始化为-1,然后将dp[0]=0,因为不一定要恰好,仔细理解一下:)
#include<iostream> #include<stdlib.h> #include<stdio.h> #include<string.h> #include<math.h> #include<vector> #include<map> #include<queue> #include<stack> #include<string> #include<algorithm> using namespace std; int a[15][106],num[106],sum[106],dp[100500]; int main() { int n,m,i,j,t,c,ans,liang,k,num1; char s[20]; map<string,int>hash; while(scanf("%d%d",&n,&m)!=EOF) { if(n==0 && m==0)break; memset(a,0,sizeof(a)); memset(num,0,sizeof(num)); memset(sum,0,sizeof(sum)); memset(s,0,sizeof(s)); hash.clear(); num1=0; for(i=1;i<=n;i++){ scanf("%s",s); if(hash[s]==0){ num1++;hash[s]=num1; } } for(i=1;i<=m;i++){ scanf("%d%s",&c,s); t=hash[s]; a[t][++num[t]]=c; sum[t]+=c; } ans=0; for(i=1;i<=num1;i++){ if(num[i]==0)continue; else{ //memset(dp,-1,sizeof(dp)); memset(dp,0,sizeof(dp)); liang=sum[i]/2; for(k=1;k<=num[i];k++){ for(j=liang;j>=a[i][k];j--){ //if(dp[j-a[i][k]]!=-1) dp[j]=max(dp[j],dp[j-a[i][k]]+a[i][k]); } } ans=ans+sum[i]-dp[liang]; } } printf("%d\n",ans); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:背包dp
原文地址:http://blog.csdn.net/kirito_acmer/article/details/46723329