HDU-1074 Doing Homework

Link: HDU-1074 Doing Homework

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

Problem solving

这道题的意思就你在做家庭作业。每种作业都有一个需要花费的时间以及截至时间,如果你完成这个作业的时间超过了截止时间,就会被罚超过时间的分数。超过1就罚一分。让你输出所有作业完成之后的最少扣多少分,以及完成作业的顺序。

注意到这里的作业数总共最多就15种。如果暴力枚举所有情况,那是的复杂度,肯定会超时。这时候就用到了状压dp(状态压缩)。
为什么叫状态压缩呢,我们用一个长度为15的二进制串中的每一位的代表每一个作业的完成情况。这样的话复杂度就会很低,

例如

就代表都未完成

就代表第一个和第三个作业完成,第二个未完成

就代表都完成

状态转移,即假设对于作业,在状态中,已完成,可以由另一个与状态基本一样,只有未完成的状态转移得到。

例如

可由 得到

不可由 得到

所以我们从遍历每一种状态,再根据状态转移确定每一种状态到达的时候所会扣的最少的分。

表示到达状态会扣的最少的分,那么显然最后作业全部完成后扣的最少的分为,关于作业完成顺序,我们添加一个辅助数组记录每次转移的状态的上一个状态,递归输出即可。

一个与状态基本一样,只有未完成的状态如何得到呢?

例如
状态为作业2,就是

Code

const int maxn = 20;
int dp[1<<maxn],fa[1<<maxn],cost[1<<maxn],d[maxn],c[maxn];
string s[maxn];
void print(int x){
    if(!x)  return ;
    print(x-(1<<fa[x]));
    cout<<s[fa[x]]<<endl;
}
int main()
{
    int t,n;
    cin>>t;
    while(t--){
        cin>>n;
        for(int i=0;i<n;i++)    cin>>s[i]>>d[i]>>c[i];
        for(int i=1;i<(1<<n);i++){
            dp[i]=0x3f3f3f3f;
            for(int j=n-1;j>=0;j--){
                int mid=(1<<j);
                if(!(i&mid))    continue;
                int val=max(0,cost[i-mid]+c[j]-d[j]);
                if(dp[i]>dp[i-mid]+val){
                    dp[i]=dp[i-mid]+val;
                    cost[i]=cost[i-mid]+c[j];
                    fa[i]=j;
                }
            }
        }
        cout<<dp[(1<<n)-1]<<endl;
        print((1<<n)-1);
    }
}