Doing Homework
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7660 Accepted Submission(s): 3454
Problem 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.
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[i]为第i个状态时的最小扣分。
怎样递推呢?
如果通过完成作业j而可以从一个状态(即i-(1<<j-1))到达另一个状态i,那么就更新下这个状态的dp值。
怎样写循环体呢?
对于每一种状态(假设有5个作业,那么状态有1,10,11,100,101…11111,共(1<<5)-1)种。),遍历每一个作业j,看能否通过完成j到达这个状态,如果可以就更新,不可以就判断下一个作业j.这里注意,由于状态我们从1开始遍历,如果想要在有多种解的情况下按升序输出作业完成顺序,那么就需要从n开始向1遍历j。这样较小的j会覆盖较大的j。
怎样记录路径呢?
详见代码中putout函数。
AC代码:
package 待解决;
import java.util.Scanner;
public class A {
public static void output(int x,int[] pre) {
if(x<1) {
return;
}
output(x-(1<<(pre[x]-1)),pre);
System.out.println(s[pre[x]]);
return;
}
public static String s[];
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
int INF=(1<<30)-1;
while(t-->0) {
int n=sc.nextInt();
int dp[]=new int[(1<<n)];
int DDL[]=new int[n+1];
int D[]=new int[(1<<n)];
s=new String[n+1];
sc.nextLine();
for(int i=1;i<=n;i++) {
s[i]=sc.next();
DDL[i]=sc.nextInt();
D[1<<(i-1)]=sc.nextInt();
//System.out.println(DDL[i]+" "+D[1<<(n-1)]);
}
int bit=(1<<n)-1;
int pre[]=new int[bit+1];
for(int i=1;i<=bit;i++) {
dp[i]=INF;
for(int j=n;j>=1;j--) {
int cur=1<<(j-1);
//System.out.println(i+" "+cur);
if((i&cur)==0) {
//System.out.println(i+" "+cur+"?");
continue;
}
//System.out.println("/");
D[i]=D[i-cur]+D[cur];//达到状态i所需的天数
int tt=D[i]-DDL[j];//通过完成作业j到达状态i所减去的分数
if(tt<0) {
tt=0;
}
if(dp[i]>dp[i-cur]+tt) {
dp[i]=dp[i-cur]+tt;
pre[i]=j;
}
}
}
System.out.println(dp[bit]);
output(bit,pre);
}
}
}