题目:点击打开链接
题意:夫妻两个人一起洗衣服,洗衣速度一样快,衣服有多种颜色,要求只有在完全洗完一种颜色的衣服后才能洗另一种颜色的,问所有的衣服都洗完最少用时是多少?
思路:01背包的变式,要求两人洗同一色衣服所用的时间尽量相近(接近总时间的二分之一),然后取用时多的那一个,累加所有颜色的结果就是答案。
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<map>
using namespace std;
string str[105];
struct node{
string color;
int time;
bool operator <(const node &a)const
{
return color<a.color;
}
}cloth[105];
int main(){
int m,n;
while(cin>>m>>n&&(m||n)){
///此处用gets会莫名的出错,估计是gets和cin连用出的错。
// char b[100];
// gets(b);
for(int i=0;i<m;i++)
cin>>str[i];
for(int i=0;i<n;i++)
cin>>cloth[i].time>>cloth[i].color;
sort(cloth,cloth+n);
cloth[n].time=0;
cloth[n++].color="##";///(未出现的字符串)小技巧 为了后面的代码更加好写,便于统一情况,统一处理。
int cnt=0,sum=0,ans=0,t[105],dp[100005];
for(int i=0;i<n-1;i++){
if(cloth[i].color==cloth[i+1].color){
t[cnt++]=cloth[i].time;
sum+=t[cnt-1];
}
else {
t[cnt++]=cloth[i].time;
sum+=t[cnt-1];
int s=sum/2;
memset(dp,0,sizeof(dp));
for(int j=0;j<cnt;j++)
for(int k=s;k>=t[j];k--)
dp[k]=max(dp[k-t[j]]+t[j],dp[k]);
ans=ans+sum-dp[s];
sum=0;
cnt=0;
}
}
cout<<ans<<endl;
}
}