HDU 1074

http://acm.hdu.edu.cn/showproblem.php?pid=1074

题目

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

题解

法一 我为人人刷表法

为了保证字典序最小,最通用的办法就是“我为人人”,倒过来考虑,顺着输出(也可以是顺着考虑,倒过来输出,反正两个方向不能相同)

https://www.cnblogs.com/sahdsg/p/10409765.html

因为倒过来考虑时,能保证最后一个选择的字典序最小,就可以保证在输出的时候第一个选择就是最小的字典序。

题目中N<=15暗示状态压缩……

AC代码

#include<bits/stdc++.h>
#define REP(r,x,y) for(register int r=(x); r<(y); r++)
#define REPE(r,x,y) for(register int r=(x); r<=(y); r++)
#define PERE(r,x,y) for(register int r=(x); r>=(y); r--)
#ifdef sahdsg
#define DBG(...) printf(__VA_ARGS__), fflush(stdout)
#else
#define DBG(...) (void)0
#endif // sahdsg
using namespace std;
char nm[17][107];
int dd[17];
int ti[17];
int dp[1<<15], tp[1<<15], ch[1<<15];
int st[15];
int main() {
	int t; scanf("%d", &t);
	while(0<t--) {
		int n; scanf("%d", &n);
		REP(i,0,n) {
			scanf("%s%d%d", nm[i], &dd[i], &ti[i]);
		}
		memset(dp,0x3f,sizeof dp); memset(tp, 0x3f, sizeof tp);
		dp[0]=0, tp[0]=0;
		REP(k,0,1<<n) {
			REP(i,0,n) {
				int x=1<<i;
				if(k&x) continue;
				int nt=ti[i]+tp[k];
				int nd=nt-dd[i];
				if(nd<0) nd=0;
				nd+=dp[k];
				if(dp[k|x]>nd) {
					ch[k|x]=i;
					tp[k|x]=nt;
					dp[k|x]=nd;
				}
			}
		}
		int p=(1<<n)-1;
		REP(i,0,n) {
			st[i]=ch[p];
			p^=1<<ch[p];
		}
		p=n;
		printf("%d
", dp[(1<<n)-1]);
		while(0<p--) {
			puts(nm[st[p]]);
		}
	}
}

法二

……

原文地址:https://www.cnblogs.com/sahdsg/p/10904917.html