Take this question as an example:
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1864
Original solution:
Http://blog.csdn.net/gaotong2055/article/details/8579388
In the above solution, DFS is too time-consuming. Even if we use typical dynamic planning, it consumes space, the array is too large, there is a lot of waste, there are too many useless loops, it will take about Ms ).
Here, the median value of map memory is used to save space and time.
# Include <stdio. h> # include <string. h >#include <iostream >#include <map> using namespace STD; double data [31]; int Len, maxa; double ans, Q; Class opt {public: int K; double D; opt (int A, double B): K (A), D (B) {} OPT () {} bool operator = (const opt & O) const {return K = O. K & D = O. d;} bool operator <(const opt & O) const {If (k = O. k) return d <O. d; elsereturn k <O. k ;}}; Map <opt, double> opts; // store the intermediate result double DFS (int K, d Ouble remain) {opt TMP (K, remain); If (OPTs [TMP]) return opts [TMP]; If (k> = Len) {return 0 ;} if (remain> = data [k]) return opts [TMP] = max (DFS (k + 1, remain-data [k]) + data [K], DFS (k + 1, remain); else return opts [TMP] = DFS (k + 1, remain); Return 0 ;}int main () {int n, m; char cc; while (scanf ("% lf % d", & Q, & N) & n! = 0) {Len = 0; ans =-1; for (INT I = 0; I <n; I ++) {scanf ("% d", & M ); double A = 0, B = 0, c = 0, temp, sum = 0; int flag = 1; while (M --) {scanf ("% C: % lf ", & CC, & temp); If (Cc = 'A') A + = temp; else if (Cc = 'B') B + = temp; else if (Cc = 'C') C ++ = temp; else flag = 0; sum + = temp ;} if (flag & sum <= 1000 & A <= 600 & B <= 600 & C <= 600) data [Len ++] = sum;} opts. clear (); ans = DFS (0, q); printf ("%. 2f \ n ", ANS );}}