题目
马上假期就要结束了,zjm还有 n 个作业,完成某个作业需要一定的时间,而且每个作业有一个截止时间,若超过截止时间,一天就要扣一分。
zjm想知道如何安排做作业,使得扣的分数最少。
Tips: 如果开始做某个作业,就必须把这个作业做完了,才能做下一个作业。
Input
有多组测试数据。第一行一个整数表示测试数据的组数
第一行一个整数 n(1<=n<=15)
接下来n行,每行一个字符串(长度不超过100) S 表示任务的名称和两个整数 D 和 C,分别表示任务的截止时间和完成任务需要的天数。
这 n 个任务是按照字符串的字典序从小到大给出。
Output
每组测试数据,输出最少扣的分数,并输出完成作业的方案,如果有多个方案,输出字典序最小的一个。
Sample Input
2
3
Computer 3 3
English 20 1
Math 3 2
3
Computer 3 3
English 6 3
Math 6 3
Sample Output
2
Computer
Math
English
3
Computer
English
Math
思路
本题数据范围比较小,考虑状态压缩。
令S表示当前完成作业的集合,则
- f[S] 表示完成 S 作业集合后被扣的最少分数;
- sum = S 作业集合对应的总时间;
- f[S|(1<<x)] = f[S] + tmp(作业 x 被扣的分数);
- c[x] = 作业 x 完成所需时间;
- d[x]=作业x的DDL;
- tmp=max(sum+c[x]–d[x],0)。
对作业按照字典序进行排序,状态S越小则其对应的字典序越小,因此 S 从小到大枚举,x 从小到大枚举即可保证字典序最小。
输出时,对每个状态 S 记录 pre[S] 表示其对应的最后一个作业,pre[S] 递归输出。
代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
using namespace std;
int const maxn=15+5;
int const Size=(1<<maxn)+5;
int const inf=0x7fffffff;
int f[Size],sum[Size],pre[Size];
struct homework{
string subject;
int ddl,days;
}h[maxn];
void output(int x){
if(x==0)
return;
output(x-(1<<pre[x]));
cout<<h[pre[x]].subject<<endl;
}
int main(){
int N,n;
scanf("%d",&N);
while(N--){
memset(f, 0, sizeof(f));memset(sum, 0, sizeof(sum));memset(pre, 0, sizeof(pre));
scanf("%d",&n);
for(int i=0;i<n;i++){
cin>>h[i].subject>>h[i].ddl>>h[i].days;
}
for(int S=1;S<=(1<<n)-1;S++){
f[S]=inf;
for(int x=0;x<n;x++){
if(S&(1<<x)){
int k=S-(1<<x);
int tmp=max(0,sum[k]+h[x].days-h[x].ddl);
f[S]=min(f[S],f[k]+tmp);
if(f[S]>=f[k]+tmp){
pre[S]=x;
sum[S]=sum[k]+h[x].days;
}
}
}
}
cout<<f[(1<<n)-1]<<endl;
output((1<<n)-1);
}
return 0;
}