Problem 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
思路
状态压缩dp,每一位代表一个状态,1为已到达,0为未到达。通过位运算遍历每一种结果。
dp的过程需要细心琢磨,需要记录已用时间和扣的分数,每次更新的时候要判断没有到达这个状态之前的旧状态,比较扣的分数是否可以更小。然后更新结果。
路径用vector存储更方便。
代码
#include<bits/stdc++.h>
using namespace std;
struct node{
string s;
int dl,need;
}p[20];
struct dp{
int score,tim;
vector<string> v;
}dp[1<<15];
int main(){
int t,n;
cin>>t;
while(t--){
cin>>n;
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++){
cin>>p[i].s >> p[i].dl >> p[i].need;
}
int e=1<<n;
for(int i=1;i<e;i++){
dp[i].score=1e9;//0x3f=63 0x3f3f3f3f>1e9不行
for(int j=0;j<n;j++){
int tmp=1<<j;
if(i&tmp){
int old=i-tmp;
int tim=dp[old].tim+p[j].need-p[j].dl;
tim=max(tim,0);
if(dp[old].score+tim<=dp[i].score){ //因为字典序最小,所以用等号
dp[i].score=dp[old].score+tim;
dp[i].tim=dp[old].tim+p[j].need;
dp[i].v=dp[old].v;
dp[i].v.push_back(p[j].s);
}
}
}
}
cout << dp[e-1].score <<endl;
for(int i=0;i<dp[e-1].v.size();i++){
cout << dp[e-1].v[i] <<endl;
}
}
return 0;
}