HDU1074-Doing Homework(状态压缩)

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

分析:

题意:
有个人要做作业,每个作业都有一个截止时间和完成这个作业必须花费的时间(超过截止时间,每超过一天就减一分),我们要做的就是对这些作业的完成顺序进行合理的调整,使得被扣的分数最少,求出被扣的分数和这些作业的顺序!

解析:
开始看这个题的时候,感觉做过,后来想起来了,在贪心那里做过,但是那里没有让输出完成的顺序,所以我们不能用贪心算法!

这里我们用了DP状态压缩,由于作业最多就15门,所以状压可以完成这个任务,开始我也想用深搜,但是想想还是算了,因为那样的时间复杂度是:nn,很大了,而我们利用状态压缩的时间复杂度是:n*2n,降低了很多了!

代码:

#include
#include
#include
#define N 20
#define INF 0x3f3f3f3f

using namespace std;

struct node{
	int deadline,len;
	string name;
};

struct point{
	int score,past,time,now;
};

point dp[(1<<15)+10];
node book[N];

void Print(int x)
{
	if(dp[x].past)
		Print(dp[x].past);
	cout<<book[dp[x].now].name<<endl;
}

int main()
{
	int T,n;
	scanf("%d",&T);
	while(T--)
	{
		memset(dp,0,sizeof(dp));
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			cin>>book[i].name>>book[i].deadline>>book[i].len;
		}
		int num=1<<n;
		for(int i=1;i<num;i++)
		{
			dp[i].score=INF;
			for(int j=n;j>0;j--)
			{
				int k=1<<(j-1);
				if(k&i)
				{
					int past=i-k;
					int add=dp[past].time+book[j].len-book[j].deadline;
					if(add<0)
						add=0;
					if(dp[past].score+add<dp[i].score)
					{
						dp[i].now=j;
						dp[i].past=past;
						dp[i].score=dp[past].score+add;
						dp[i].time=dp[past].time+book[j].len;
					}
				}
			}
		}
		cout<<dp[(1<<n)-1].score<<endl;;
		Print((1<<n)-1);
	}
	return 0;
}

你可能感兴趣的:(动态-状态压缩,算法,动态规划)