用C++编译器优化实现记忆化 发表于 2016-04-07 | 分类于 ACM | 如果要实现输出fib(100)%1200007,可以实现用编译器来自动记忆化。 123456789101112131415161718#include<iostream>using namespace std;template<int x>struct fib{ static const int val = (fib<x - 1>::val + fib<x - 2>::val) % 1200007;}template<>struct fib<0>{ static const int val = 1;}template<>struct fib<1>{ static const int val = 1;}int main(){ cout << fib<100>::val << endl; return 0;} 编译器在编译的时候就会对这个进行优化,会非常快速算出来。 【工程代码】 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#include <iostream>using namespace std;template<int x>struct fib{ static const int val = (fib<x - 1>::val + fib<x - 2>::val) % 1200007;};template<>struct fib<0>{ static const int val = 0;};template<>struct fib<1>{ static const int val = 1;};int fib2(int x){ if (x < 2) return x; else return (fib2(x - 1) + fib2(x - 2)) % 1200007;}int fib3(int x){ int a = 0, b = 1,c; if (x == 0) b = 0; else if (x == 1) b = 1; else{ for (int i = 2; i <= x; i++) { c = a + b; a = b; b = c % 1200007; } } return b;}class fib4{ int *nums; bool *labels; int n; int calc(int x){ if (labels[x]) return nums[x]; nums[x] = calc(x - 1) + calc(x - 2); labels[x] = 1; return nums[x] % 1200007; }public: fib4(int x){ n = x; nums = new int [n]; labels = new bool [n]; memset(labels, 0, sizeof(char) * n); labels[0] = labels[1] = 1; nums[0] = 0; nums[1] = 1; } int getFib(){ return calc(n); }};int main(){ cout << fib<100>::val << endl; cout << fib3(100) << endl; fib4 f = fib4(100); cout << f.getFib() << endl; return 0;}