题目链接
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.
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.
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.
典型的状压 DP ~ 我们直接枚举所有情况,每次更新一下最优值即可,用 d p [ i ] . s c o r e dp[i].score dp[i].score 记录最小扣分数,则有状态转移方程: r e s = m a x ( d p [ k ] . t i m e + c o u r s e [ j ] . c o s t − c o u r s e [ j ] . d e a d l i n e , 0 ) , j ∈ [ 0 , n ) res=max(dp[k].time+course[j].cost-course[j].deadline,0),j\in [0,n) res=max(dp[k].time+course[j].cost−course[j].deadline,0),j∈[0,n) d p [ i ] . s c o r e = m i n ( d p [ i ] . s c o r e , d p [ k ] . s c o r e + r e s ) dp[i].score=min(dp[i].score,dp[k].score+res) dp[i].score=min(dp[i].score,dp[k].score+res) 但是题目还有一个额外要求,就是输出路径,因为题目已经规定输入样例就是字典序升序的,所以无需考虑字典序。输出可以用 DFS 输出,所以在 DP 的过程中记录每个点(把科目当作结点)的前驱结点和现有结点即可,AC代码如下:
#include<bits/stdc++.h> using namespace std; const int inf=1e9; struct node1{ char name[105]; int deadline,cost; }course[20]; struct node2{ int time,score,pre,now; }dp[1<<15]; void print(int k){ if(!k) return; print(dp[k].pre); printf("%s\n",course[dp[k].now].name); } int t,n; int main(){ scanf("%d",&t); while(t--){ memset(dp,0,sizeof(dp)); scanf("%d",&n); for(int i=0;i<n;i++) scanf("%s%d%d",course[i].name,&course[i].deadline,&course[i].cost); for(int i=1;i<(1<<n);i++){ dp[i].score=inf; for(int j=n-1;j>=0;j--){ if(i&(1<<j)){ int k=i-(1<<j); int res=max(dp[k].time+course[j].cost-course[j].deadline,0); if(dp[k].score+res<dp[i].score){ dp[i].score=dp[k].score+res; dp[i].now=j; dp[i].pre=k; dp[i].time=dp[k].time+course[j].cost; } } } } printf("%d\n",dp[(1<<n)-1].score); print((1<<n)-1); } }