Doing Homework
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4416 Accepted Submission(s): 1787
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.
2 3 Computer 3 3 English 20 1 Math 3 2 3 Computer 3 3 English 6 3 Math 6 3
1. 分析
看到题目,马上想到的一种解法是,暴力搜索,枚举各种可能的排列方式,然后计算最小值。但是其复杂度为n!,此处n为15,那么肯定超时了。但是使用状态压缩dp可以将复杂度降低到n*2^n(因为穷举搜索没有注意到各个状态之间的转换关系,而造成重复计算)。
思路:想要用动态规划,就需要保存中间状态的结果,我们可以用一个int型数字来表示一个状态,int中的第i位表示第i个任务有没有完成,因而可以用15位来保存该问题的所有状态,又每个任务有两个状态(完成或没完成),则该问题总共有2^15个状态,可以用数组dp来保存
用dp[i]表示完成i的二进制表示所对应的任务最少需要扣掉的分数,则有:
在实现上述算法时,需要注意,当求dp[i]时,需要dp[i-(1<<j)]都要已经被求出,易知,i-(1<<j)<i,因此,可以从1开始往上求。(注意求值顺序)dp[i] = min(dp[i-(1<<j)] + cost) j=0,1,2,3,……
其中,i-(1<<j) 表示将i的第j位置为0,即表示可以从i-(1<<j)这个状态可以转换到i所表示的状态,cost表示接着(i-(1<<j))这个状态,完成第j个任务所扣掉的分数(此题目由于需要,所以dp数组中保存的是数据结构,而不是单一的整数)
2. AC代码
#include <iostream>
#include <cstring>
using namespace std;
#define COURSE_NUM 15
#define MAX 0x7FFF
struct Course {
int deadline;
int time;
char name[101];
} course[COURSE_NUM];
struct Node {
int pre;
int cost;
int cur_time;
} dp[MAX];
int main() {
int case_num;
cin >> case_num;
while (case_num--) {
memset(dp, 0, sizeof(dp));
memset(course, 0, sizeof(course));
int n;
cin >> n;
//for (int i=1; i<=n; i++)
for (int i=0; i<n; ++i)
cin >> course[i].name >> course[i].deadline >> course[i].time;
int state_num = 1<<n;
for (int i=1; i<state_num; ++i) {
for (int j=0; j<n; ++j) {
if (i&(1<<j)) {
//int pre = i&(^(1<<j));
int pre = i-(1<<j);
//int finished_time = dp[pre].cur_time + course[i].time;
int finished_time = dp[pre].cur_time + course[j].time;
//int cost = finished_time - course[i].deadline;
int cost = finished_time - course[j].deadline;
if (cost < 0) cost = 0;
cost += dp[pre].cost;
// j从零开始,表示后做序号小的课程,而题目要求相反
// if (dp[i].cur_time==0 || cost < dp[i].cost) {
if (dp[i].cur_time==0 || cost <= dp[i].cost) {
dp[i].cur_time = finished_time;
dp[i].cost = cost;
dp[i].pre = j;
}
}
}
}
cout << dp[state_num-1].cost << endl;
int a[COURSE_NUM];
int tmp = state_num-1;
int index = 0;
while(tmp) {
a[index++] = dp[tmp].pre;
tmp = tmp-(1<<dp[tmp].pre);
}
while (index>0)
cout << course[a[--index]].name << endl;
}
return 0;
}
5万+


 --- HDU 1074 **&spm=1001.2101.3001.11974&articleId=17141967&d=1&t=3&u=c6583cf2e23544b7ac18e4488ee78d08)

被折叠的 条评论
为什么被折叠?



