#include <iostream> #include <initializer_list> #include <utility> #include <typeinfo> #include <vector> #include <iterator>
enum MValue:unsigned long { MAXVALUE=1000000 };
template<typename T=long> class MatrixChainOrder{ //矩阵链最优顺序计算. private: std::vector<std::vector<T>> M; std::vector<std::vector<T>> S; std::vector<T> chains; public: template<typename U=long> MatrixChainOrder(const std::initializer_list<U>& il)noexcept(true); //([&theIl]()->bool { (theIl.size()==0)?true:false}); ~MatrixChainOrder()noexcept(true); void chainOrder(); void print(); };
template<typename T> template<typename U> MatrixChainOrder<T>::MatrixChainOrder(const std::initializer_list<U>& il)noexcept(true) :chains(il) { int temp=chains.size(); std::vector<T> tempVec(temp); //初始化一个有temp个元素的vector; for(int i=0; i<temp; ++i){ this->M.push_back(tempVec); this->S.push_back(tempVec); } }
template<typename T> MatrixChainOrder<T>::~MatrixChainOrder()noexcept(true) { int temp=M.size(); for(int i=0; i<temp; ++temp){ M[i].clear(); S[i].clear(); } M.clear(); S.clear(); std::cout<<"destroy it"<<std::endl; }
template<typename T> void MatrixChainOrder<T>::chainOrder() { int n=this->chains.size();//n是矩阵链摊开后的大小.例如:A(x,y),A1(x1,y1),那么chains={x*y*x1*y1}; /* 假设矩阵Ai........Aj,之间存在最优相乘代价.最优分割点k且 i<=k<j; M[i][j]=M[i][k]+M[k+1][j]+x*x1*y1; */ int j; int q;//a temporary value. if(typeid(T)==typeid(long int) || typeid(T)==typeid(double)){ std::cout<<"success to enter"<<std::endl; for(int i=0; i<n; ++i){ this->M[i][i]=0;//M[1][1], M[2][2], M[3][3]; M相当于计算chains中i-i所需要的代价. } for(int l=2; l<n; ++l){//当chains内至少有两个元素的时候.假设n=6; for(int i=0; i<n-l+1; ++i){//l=2,i=5,4,3...1; j=i+l-1;//j得到的是6,5,4,3,2,1.... M[i][j]=MAXVALUE; for(int k=i; i<j; ++i){//k=0,1,2,...5; 2...4; .... q=M[i][k]+M[k+1][j]+chains[i-1]*chains[k]*chains[j];//计算从i-j的最优代价. if(q < M[i][j]){ M[i][j]=q; S[i][j]=k;//记录最佳分割点. } } } } } } template<typename T> void MatrixChainOrder<T>::print() { std::ostream_iterator<T> out(std::cout, " "); std::cout<<"print M:"<<std::endl; if(M.empty()){ std::cout<<"chains are less than 1"<<std::endl; }else{ for(auto tempM: this->M){ for(auto tempT:tempM){ *(out++)=tempT; } } std::cout<<"\n"<<"print S:"<<std::endl; for(auto tempS: this->S){ for(auto tempT:tempS){ *(out++)=tempT; } } } } int main() { MatrixChainOrder<> myChains( {30l, 35l, 35l, 15l, 15l, 5l, 5l, 10l, 10l, 20l, 20l, 25l} ); myChains.chainOrder(); myChains.print(); return 0; }