SPOJ Can you answer these queries I

后端 未结 1 1705
旧时难觅i
旧时难觅i 2021-01-21 22:11

I am trying to solve this problem on SPOJ. I found this problem in the segment tree section, so I am pretty sure that there could be some possible solution that uses segment tre

1条回答
  •  清歌不尽
    2021-01-21 22:56

    You can solve it by building a segment tree on the prefix sums

    sum[i] = sum[i - 1] + a[i] 
    

    and then keeping the following information in a node:

    node.min   = the minimum sum[i], x <= i <= y 
                ([x, y] being the interval associated to node)
               = minimum(node.left.min, node.right.min)
    node.max   = same but with maximum
    
    node.best  = maximum(node.left.best,
                         node.right.best,
                         node.right.max - node.left.min
                        )
    

    Basically, the best field gives you the sum of the maximum sum subarray in the associated interval. This is either one of the maximum sum subarrays in the two child nodes, or a sequence that crosses both of the child intervals, which is obtained by subtracting the minimum in the left child from the maximum in the right child, which we also do in a possible linear solution: find the minimum sum[j], j < i for each each i, then compare sum[i] - sum[j] with the global max.

    Now, to answer a query you will need to consider the nodes whose associated intervals make up your queried interval and do something similar to how we built the tree. You should try to figure it out on your own, but let me know if you get stuck somewhere.

    0 讨论(0)
提交回复
热议问题