HDU 1074-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
分析:
宿題をしなければならない人がいます.宿題ごとに締め切り時間とこの宿題を完成するのにかかる時間(締め切り時間を超えて、一日を超えるたびに1点減らす)があります.私たちがしなければならないのは、これらの宿題の完成順序を合理的に調整して、差し引かれた点数を最小限に抑え、差し引かれた点数とこれらの宿題の順序を求めることです.
解析:この問題を見始めたとき、やったことがあると感じて、それから思い出して、貪欲なところでやったことがありますが、そこには出力を完成させる順番がないので、貪欲なアルゴリズムは使えません!
ここで私たちはDP状態圧縮を使って、作業がせいぜい15ドアなので、状圧はこの任務を完成することができて、最初は私も深く探したいと思っていましたが、考えてみればやめましょう.そのような時間複雑度は:nn、大きくなったので、私たちが状態圧縮を利用する時間複雑度は:n*2 nで、ずいぶん下がったからです.
コード:
#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;
}