编程之美2.14, 2.15节。这个问题在编程珠玑中的算法章有很深入的分析。
可以试解下题:
下面为求maximum sum on torus的代码:
template<class It>typename iterator_traits<It>::value_typemaxsum(It first, It last) { typedef typename iterator_traits<It>::value_type value_type; value_type maxsofar, maxatend; maxsofar = maxatend = *first++; for (It it = first; it != last; ++it) { maxatend = max(maxatend + *it, *it); maxsofar = max(maxsofar, maxatend); } return maxsofar;}template<class It>typename iterator_traits<It>::value_typeminsum(It first, It last) { typedef typename iterator_traits<It>::value_type value_type; value_type minsofar, minatend; minsofar = minatend = *first++; for (It it = first; it != last; ++it) { minatend = min(minatend + *it, *it); minsofar = min(minsofar, minatend); } return minsofar;}template<class It>typename iterator_traits<It>::value_typesum(It first, It last) { typename iterator_traits<It>::value_type s = 0; for (It it = first; it != last; ++it) s += *it; return s;}template<class It>typename iterator_traits<It>::value_typerotatedmaxsum(It first, It last) { return max(maxsum(first, last), sum(first, last) - minsum(first, last));}template<class It>typename iterator_traits<It>::value_typetorusmaxsum(It first, It last, size_t row) { typedef typename iterator_traits<It>::value_type value_type; size_t col = distance(first, last)/row; vector<value_type> sums(col, 0); for (size_t i = 0; i < row; ++i) { for (size_t j = 0, p = i*col; j < col; ++j) { It it = first; advance(it, p + j); sums[j] += *it; } } value_type r = *first; for (size_t i = 0; i < row; ++i) { vector<value_type> vec(col, 0); for (size_t j = i; j < row; ++j) { for (size_t k = 0, p = j*col; k < col; ++k) { It it = first; advance(it, p + k); vec[k] += *it; } r = max(r, rotatedmaxsum(vec.begin(), vec.end())); vector<value_type> rvec(col, 0); for (size_t i = 0; i < col; ++i) rvec[i] = sums[i] - vec[i]; r = max(r, rotatedmaxsum(rvec.begin(), rvec.end())); } } return r;}
来源:https://www.cnblogs.com/acmaru/archive/2011/03/21/1990800.html