D - Doing Homework
InputThe 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.
OutputFor 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
Hint
In the second test case, both Computer->English->Math and Computer->Math->English leads to reduce 3 points, but the word "English" appears earlier than the word "Math", so we choose the first order. That is so-called alphabet order.
题意:
给n门作业,给一个做完作业的deadline 和 花费的时间, 超过时间后,每超过一天扣一分,求总扣分最少。(题目保证按科目名称字典序递增顺序输入)
思路:
作业最多有15门,每门作业都只有做与不做两种状态,如果枚举每种状态,显然会T,这里就可以想一下状态压缩。
因为每门作业都只有两种状态,0表示没做,1表示做,因此就可以转化成二进制的形式来操作。
用 k 表示上一个状态, i 表示当前状态对每次操作计算cost ,如果当前状态花费的时间比正在做的作业的dealine大,cost=time[k]-d[j],否则cost = 0; 则 dp[i]= min(dp[k] + cost, dp[i]),当dp[i] >= dp[k]+cost 时,令dp[i] = dp[k]+cost ,同时保存路径。
过题代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <functional>
//#include
using namespace std;
const int maxn=1<<15,inf=(1<<30);
struct node{
int d,c;
char name[110];
}a[maxn];
int tim[maxn],dp[maxn],pre[maxn];
int T,n,cost;
void print(int k){
if(k==0) return;
print(pre[k]);
k-=pre[k];
for (int i=0;i<n;i++)
if(k&1<<i) printf("%s
",a[i].name);
}
int main(){
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for (int i=0;i<n;i++)
scanf("%s%d%d",a[i].name,&a[i].d,&a[i].c);
int m=1<<n;
// memset(dp,0x3f,sizeof(dp));
for (int i=0;i<m;i++) dp[i]=inf;
tim[0]=dp[0]=0;
for (int i=1;i<m;i++){
for (int j=0;j<n;j++){
if((i & 1 << j)==0) continue;
int k = i-(1 << j);
tim[i] = tim[k]+a[j].c;
cost = max(tim[i]-a[j].d,0);
if(cost+dp[k] <= dp[i]){ // “=” 因为需要字典序最小,所以保存时保存一个较大的科目,这样保证了先做的字典序最小
dp[i] = cost+dp[k];
pre[i] = k;
}
}
}
// for (int i=0;i<m;i++)
// printf("%d %d
",i,dp[i]);
printf("%d
",dp[m-1]);
print(m-1);
}
return 0;
}