hdu 1074 状压dp

//2015.7.16 首A

 1 #include "bits/stdc++.h"
 2 using namespace std;
 3 int T;
 4 int N;
 5 char subject[20][110];
 6 int deadline[20], spend[20];
 7 int dp[40000], choice[40000], tot_spend[40000];
 8 
 9 int ans[20], tot;
10 
11 const int INF = 0x3f3f3f3f;
12 
13 void print_2(int val)
14 {
15     if(val) {
16         print_2(val >> 1);
17         printf("%d", val & 1);
18     }
19 }
20 
21 int main()
22 {
23     scanf("%d", &T);
24     while(T--) {
25         memset(dp, 0x3f, sizeof(dp));
26         memset(choice, 0, sizeof(choice));
27         dp[0] = 0;
28         scanf("%d", &N);
29 
30         int i;
31         for(i = 1; i <= N; ++i) {
32             scanf("%s%d%d", subject[i], &deadline[i], &spend[i]);
33         }
34         int s, tot_s = (1 << N) - 1;
35         int item, step_s, pre_s;
36         for(s = 1; s <= tot_s; ++s) {
37             for(item = 1; item <= N; ++item) {
38                 step_s = 1 << (item - 1);
39 
40                 if(step_s & s) {
41                     pre_s = s ^ step_s;
42                     if(dp[s] == INF) {
43                         tot_spend[s] = tot_spend[pre_s] + spend[item];
44                     }
45                     int tmp = tot_spend[s] - deadline[item];
46 
47                     if(dp[s] > dp[pre_s] + (tmp < 0? 0: tmp) || (dp[s] == dp[pre_s] + (tmp < 0? 0: tmp) && strcmp(subject[item], subject[choice[s]]) > 0)) {
48                         dp[s] = dp[pre_s] + (tmp < 0? 0: tmp);
49                         choice[s] = item;
50 //                        printf("dp[");
51 //                        print_2(s);
52 //                        printf("] == ");
53 //
54 //                        printf("dp[");
55 //                        if(pre_s)
56 //                            print_2(pre_s);
57 //                        else
58 //                            printf("0");
59 //                        printf("] + %d  == %d\n", tmp < 0? 0: tmp, dp[s]);
60                     }
61                 }
62             }
63         }
64         tot = 0;
65         for(s = tot_s; s; s ^= (1 << (choice[s] - 1))) {
66             ++tot;
67             ans[tot] = choice[s];
68         }
69         printf("%d\n", dp[tot_s]);
70         for(i = tot; i >= 1; --i) {
71             printf("%s\n", subject[ans[i]]);
72         }
73     }
74 }

 

posted @ 2015-07-16 15:18  AC_Phoenix  阅读(151)  评论(0编辑  收藏  举报