现在的位置: 首页 > 综合 > 正文

Poj 3211 Washing Clothes

2018年01月15日 ⁄ 综合 ⁄ 共 2267字 ⁄ 字号 评论关闭

Washing Clothes

Time Limit:1000MS

Memory Limit:131072K

Total Submissions:7125

Accepted:2111

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背包的策略,求出洗每类衣服的最少时间,然后相加就好了。

求每类衣服的最少时间用的是01背包求的解,转换求所能的时间组合的小于总时间的一半的最小值a,然后每类衣服的最少时间即为sum-a

想要把一系列的具有某种性质数量上尽量均分,可采用背包的常规解法求可达的小于sum/2的最大数


#include<stdio.h>
#include<string.h>

char ch[12][12];
int c[12][101];
int max[12];
int f[100001];

int main(void)
{
	int N,M;
	freopen("d:\\in.txt","r",stdin);
	while(scanf("%d%d",&M,&N),N||M)
	{
		int i,j,k,ti,s=0;
		char tmp[20];
		for(i=1;i<=M;i++)
			scanf("%s",ch[i]);
		for(i=1;i<=M;i++)
		{
			c[i][0]=0;
			max[i]=0;
		}
		for(i=1;i<=N;i++)
		{
			scanf("%d%s",&ti,tmp);
			for(j=1;j<=M;j++)
			{
				if(!strcmp(tmp,ch[j]))
				{
					c[j][0]++;
					c[j][c[j][0]]=ti;
					max[j]+=ti;
					break;
				}
			}
		}
		for(i=1;i<=M;i++)
		{
			memset(f,0,sizeof(f));
			f[0]=1;
			for(j=1;j<=c[i][0];j++)
			{
				for(k=max[i]/2;k>=c[i][j];k--)
				{
					if(f[k-c[i][j]])
						f[k]=1;
				}
			}
			j=max[i]/2;
			while(!f[j])
				j--;
			s+=(max[i]-j);
		}
		printf("%d\n",s);
	}
	return 0;
}


抱歉!评论已关闭.