// SASSolver.h // tom bailey 15 oct 04 // tom bailey 16 oct 08 // Declare a base class and several concrete classes of objects // that solve the best subarray sum problem for a sequence // stored in a vector. #include using std::string; #include using std::ostream; #include using std::vector; class SASSolver { public: virtual double bestSum( const vector & ) = 0; virtual void description( ostream & ) const; }; SASSolver & getAlgorithm(); // prints a description of the algorithm ostream & operator<<( ostream &, const SASSolver & ); // SASOne solves the problem using the simple, but slow, // technique of finding the sum of every possible segment // of the container. class SASOne: public SASSolver { public: // return the best sum for any subsequence in the vector. double bestSum( const vector & ); void description( ostream & ) const; private: template< typename IT > double sum( IT, IT ); }; // SASFour solves the same problem recursively by tracking // four attributes of a segment. // ResType records and manipulates four attributes of a // segment of a vector. // ResType stores and manipulates the Results produced // by calls to the SASFour helper method used by the // SASFour.bestSum method. // operator + combines the attributes for // two adjacent container segments into the // attributes for one segment consisting of the // union of the two segments. class ResType { double best; double sum; double bestToLeft; double bestToRight; public: ResType(); template< typename IT > ResType( IT ); ResType operator += ( const ResType & ); double bestSAS() const; }; ResType operator + ( const ResType &, const ResType & ); class SASFour: public SASSolver { public: double bestSum( const vector & ); void description( ostream & ) const; private: template< typename IT > ResType bestSum( IT, IT ); };