`
Simone_chou
  • 浏览: 184658 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

Washing Clothes(01背包)

 
阅读更多
Washing Clothes
Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 8268   Accepted: 2565

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

 

    题意:

    两人一起洗衣服,每次洗只能洗相同的颜色,求最短洗完衣服的时间。

 

    思路:

    01背包。两人同样一起洗衣服,所以对于一种颜色的衣服最好能平均分配时间,不能平均则两人时间最接近且最接近平均总时间。

 

    AC:

 

#include<stdio.h>
#include<string.h>
typedef struct
{
    char color[15];  //存颜色的名字
    int sumtime;     //存总时间
    int sumnum;      //存总件数
    int each[105];   //存每一件的时间
}node;
node no[15];
int dp[100000];

int main()
{
    int n,m,ans;
    while(scanf("%d%d",&n,&m)!=EOF&&(n+m))
    {
      ans=0;
      memset(no,0,sizeof(no));
      for(int i=1;i<=n;i++)
      {
        scanf("%s",no[i].color);
        no[i].sumnum=0;
        no[i].sumtime=0;
      }
//颜色种类
      for(int i=1;i<=m;i++)
      {
        int t;
        char str[15];
        scanf("%d%s",&t,str);
        for(int j=1;j<=n;j++)
          if(!strcmp(str,no[j].color))
          {
           no[j].sumnum++;
           no[j].each[no[j].sumnum]=t;
           no[j].sumtime+=t;
          }
      }
//输入每件衣服资料
      for(int k=1;k<=n;k++)
      {
       memset(dp,0,sizeof(dp));
       int half=no[k].sumtime/2;
       for(int i=1;i<=no[k].sumnum;i++)
         for(int j=half;j>=no[k].each[i];j--)
           if(dp[j]<dp[j-no[k].each[i]]+no[k].each[i])
           dp[j]=dp[j-no[k].each[i]]+no[k].each[i];
       ans+=(no[k].sumtime-dp[half]);
      }
//01背包
      printf("%d\n",ans);
    }
    return 0;
}

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics