题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1074
题目大意:给一堆作业的ddl和所需完成时间,如果超时就要多花1的代价,问最后最少需要花多少代价,并输出完成作业的顺序。
题目思路:状压dp,用连续15位表示作业完成情况,1为做了,0为没做,然后从1到(1<<n)-1,通过思考可以发现,多数字的情况出现时,比它少一个数字的情况必已经算过。对于每种情况,可以发现完成所有这些作业的总时间是固定的,然而代价跟顺序有关系。枚举一个状态中所有的1,设它是最后完成的,其他的完成情况前面已经算过。dp[i-temp].time是指除了这个作业外,其他已完成作业所需的总时间,然后加上他所需的时间-他的ddl,就是按照该顺序它完成该作业所需的代价。然后就按照这个转移即可。
以下是代码:
#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
using namespace std;
#define inf 0x3f3f3f3f
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
const int MAXN = (1<<15)+5;
const int MOD = 1e9+7;
struct node{
char name[105];
int d,c;
}a[MAXN];
struct nod{
int now,pre,time,cost;
}dp[MAXN];
int main(){
int t,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
memset(dp,0,sizeof(dp));
rep(i,0,n-1){
scanf("%s%d%d",a[i].name,&a[i].d,&a[i].c);
}
int endd=(1<<n)-1;
rep(i,1,endd){
dp[i].cost=inf;
per(j,n-1,0){
int temp=1<<j;
if(temp&i){
int st=max(0,dp[i-temp].time+a[j].c-a[j].d);
if(st+dp[i-temp].cost<dp[i].cost){
dp[i].cost=st+dp[i-temp].cost;
dp[i].time=dp[i-temp].time+a[j].c;
dp[i].now=j;
dp[i].pre=i-temp;
}
}
}
}
printf("%d\n",dp[endd].cost);
stack<string>s;
int i=endd;
while(i!=0){
s.push(a[dp[i].now].name);
i=dp[i].pre;
}
while(!s.empty()){
cout<<s.top()<<endl;
s.pop();
}
}
return 0;
}