# 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.

2
3
Computer 3 3
English 20 1
Math 3 2
3
Computer 3 3
English 6 3
Math 6 3

2
Computer
Math
English
3
Computer
English
Math

## 解决思路

$F[i]=min(F[j]+max(Nowtime[j]+Costtime[k]-Deadline[k],0))$

## 代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxN=20;
const int inf=2147483647;

int n;
char Name[maxN][200];
int Costtime[maxN];
int F[1<<16];
int Nowtime[1<<16];
int Path[1<<16];

void outp(int x);

int main()
{
int T;
scanf("%d",&T);
while (T--)
{
scanf("%d",&n);
for (int i=0;i<n;i++)
int MAX=1<<n;//MAX就是最终状态+1
memset(F,127,sizeof(F));
memset(Nowtime,0,sizeof(Nowtime));
F[0]=0;//初始状态
Nowtime[0]=0;
Path[0]=-1;
for (int i=1;i<MAX;i++)//枚举每一种状态
{
for (int j=n-1;j>=0;j--)//为了保证字典序，这里要从大到小，因为要让这个新做的作业尽量靠后
{
int now=1<<j;
if ((i&now)==0)//如果这个状态不要求做第j个作业（也就是i的这一位为0），则不会从其转移过来
continue;
//cout<<i<<" "<<j<<endl;
now=now^i;//这里的now就变成了我们要找的可以转移到i的前面的状态
if (F[now]+delta<F[i])//更新最优解，并记录信息
{
F[i]=F[now]+delta;
Nowtime[i]=Nowtime[now]+Costtime[j];
Path[i]=j;
}
}
}
printf("%d\n",F[MAX-1]);//输出
outp(MAX-1);//输出方案
}
return 0;
}

void outp(int x)//递归输出方案
{
int k=Path[x];
if (k!=-1)
outp(x^(1<<k));
if (k==-1)
return;
printf("%s\n",Name[k]);
return;
}
posted @ 2017-08-24 14:24 SYCstudio 阅读(...) 评论(...) 编辑 收藏