Use Map for Memory search for Dynamic Planning Optimization

Source: Internet
Author: User

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 );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.