zoukankan      html  css  js  c++  java
  • 分治法 解决最大字段和问题

    分治法求解最大字段和问题

    1 问题描述

      给定由n个整数(可能由负数)组成的序列(a1, a2,...,an),最大字段和问题求 该序列中连续子段和的最大值,并找出这个连续子段。

    2 使用python编程解决,具体代码如下

    # 求出最大子段和, 以及最大子段和 对应的位置,返回的位置 可能时乱序,由于是连续的,找出最大值和最小值,即确定位置
    def max_sum(row_data, left, right):
        sum_max_sub = 0
        position_list = []
        if left == right:
            if row_data[left] > 0:
                sum_max_sub = row_data[left]
                position_list.append(left)  # 记录下位置
            else:
                sum_max_sub = 0
        else:     # 三种情况
            center = (left + right) // 2
            left_sum, left_position = max_sum(row_data, left, center)     # 左侧 连续子段最大和
            right_sum, right_position = max_sum(row_data, center+1, right)  # 右侧 连续子段最大和
    
            # 第三种情况, 从中间向两侧 的连续子段最大和
            s1 = 0  # 用来记录 子段和
            lefts = 0
            for i in range(center, left-1, -1):
                lefts += row_data[i]
                if lefts > s1:
                    s1 = lefts
                    position_list.append(i)
    
            s2 = 0  # 用来记录 子段和
            rights = 0
            for j in range(center+1, right+1):
                rights += row_data[j]
                if rights > s2:
                    s2 = rights    # 在这个 找位置吗??
                    position_list.append(j)
    
            sum_max_sub = s1 + s2
            if sum_max_sub < left_sum:
                sum_max_sub = left_sum
                position_list = left_position
            if sum_max_sub < right_sum:
                sum_max_sub = right_sum
                position_list = right_position
    
        print("最大字段和为:{}".format(sum_max_sub))
        print("最大字段和对应的索引:{}".format(position_list))
        return sum_max_sub, position_list
    
    
    def max_main():
        row_data = [-20, 11, -4, 13, -5, -2]
        max_sum(row_data, 0, len(row_data)-1)
    
    
    max_main()
  • 相关阅读:
    POJ 2585 Window Pains 拓扑排序
    hrbust 2069 萌萌哒十五酱的衣服~ stl
    CodeForces 785D Anton and School
    CodeForces 816C Karen and Game
    CodeForces 758C Unfair Poll 模拟
    CodeForces 746D Green and Black Tea 有坑
    CodeForces 811C Vladik and Memorable Trip dp
    栈 队列 (面向对象列表实现)
    员工信息表 信息检索(模糊查询)
    员工信息表 查询 周末写(很简单)
  • 原文地址:https://www.cnblogs.com/generalLi/p/9898540.html
Copyright © 2011-2022 走看看