Description
Ignatius has just come back school from the 30th ACM/ICPC. Now he has a lot of homework to do. Every teacher gives him a deadline of handing in the homework. If Ignatius hands in the homework after the deadline, the teacher will reduce his score of the final test, 1 day for 1 point. And as you know, doing homework always takes a long time. So Ignatius wants you to help him to arrange the order of doing homework to minimize the reduced score.
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case start with a positive integer N(1<=N<=15) which indicate the number of homework. Then N lines follow. Each line contains a string S(the subject's name, each string will at most has 100 characters) and two integers D(the deadline of the subject), C(how many days will it take Ignatius to finish this subject's homework).
Note: All the subject names are given in the alphabet increasing order. So you may process the problem much easier.
Output
For each test case, you should output the smallest total reduced score, then give out the order of the subjects, one subject in a line. If there are more than one orders, you should output the alphabet smallest one.
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
题目大意:
有N门课,每门课还有D天就要交,他需要写C天,超过期限还没写完就每多一天扣一分,问怎么分配做每门课的作业才能让扣掉的总分最少。
分析:
注意到这里的N最大是15,那么我们可以枚举完成不同作业的顺序。
采用二进制状态压缩记录当前状态下作业的完成情况,例如101表示第一门和第三门作业已完成。
继续考虑状态转移,101有可能从001做完了第三门课的作业转换而来,也有可能是从100做完了第一门课的作业转换而来,这样状态转移就好表示了。
具体解释见代码。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
using namespace std;
typedef long long ll;
const int maxn = 100000 + 5;
const int INF = 0x3f3f3f3f;
struct node//记录课程作业信息
{
string s;//课程名称
int ddl;//作业deadline
int cost;//作业耗时
}w[20];
struct d//用于DP
{
int time;//该状态下做完指定作业的时间
int score;//该状态下扣除的分数
int pre,now;//用于记录做作业的顺序
}dp[1<<15];
void Print(int state){//打印做作业的顺序
if(!state) return;
Print(dp[state].pre);
cout<<w[dp[state].now].s<<endl;
}
int main() {
int t,n,d,c;
char str[105];
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%s %d %d",str,&d,&c);
w[i].s=str;
w[i].ddl=d;
w[i].cost=c;
}
for(int i=1;i<(1<<n);i++){//枚举每个状态
dp[i].score=INF;//初始化扣除的分数为最大值
for(int j=n-1;j>=0;j--){//从后往前枚举到达这一状态时所做的课程作业(做了哪一门课的作业到达这一状态的),为了满足最后输出的顺序为字典最小序
if((i&(1<<j))){//i状态下第j+1门作业已完成
int pstate=i-(1<<j);//第j+1门作业未完成的前一状态
int tmp=dp[pstate].time+w[j+1].cost-w[j+1].ddl;//扣除的分数
if(tmp<0) tmp=0;//扣除的分数不能为负
if(tmp+dp[pstate].score<dp[i].score){//更新i状态下的信息
dp[i].time=dp[pstate].time+w[j+1].cost;
dp[i].score=tmp+dp[pstate].score;
dp[i].now=j+1;//当前刚做完j+1
dp[i].pre=pstate;//记录前一状态
}
}
}
}
cout<<dp[(1<<n)-1].score<<endl;
Print((1<<n)-1);
}
return 0;
}