最大和子数组

这一生的挚爱 提交于 2020-01-22 12:25:42

编程之美2.14, 2.15节。这个问题在编程珠玑中的算法章有很深入的分析。

可以试解下题:

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=448

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=44

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=1768

下面为求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;}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!