POJ3211Washing Clothes题解动态规划DP

Washing Clothes
Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 5459   Accepted: 1417

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

Source

POJ Monthly--2007.04.01, dearboy
刚开始题意理解错误以为是贪心
对每种颜色的衣服进行01背包DP,背包容量为sum/2
洗这种颜色衣服的时间是sum-dp[sum/2]
代码:
#include<cstdio> #include<string> #include<map> #include<algorithm> using namespace std; struct node {int a[105],n,t;}c[10]; int main() { int n,m,i,j,k,t,x; while(scanf("%d%d",&n,&m),n+m) { int ans=0; char s[15]; map<string,int> q; for(i=0;i<n;i++) { scanf("%s",s); c[q[s]=i].t=c[i].n=0; } while(m--) { scanf("%d%s",&t,s); x=q[s]; c[x].t+=c[x].a[c[x].n++]=t; } for(k=0;k<n;k++) { int d[10005]={0}; for(i=0;i<c[k].n;i++) for(j=c[k].t/2;j>=c[k].a[i];j--) d[j]=max(d[j],d[j-c[k].a[i]]+c[k].a[i]); ans+=c[k].t-d[c[k].t/2]; } printf("%d/n",ans); } }

你可能感兴趣的:(POJ3211Washing Clothes题解动态规划DP)