GSS1 - Can you answer these queries I
You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1 ≤ N ≤ 50000 ). A query is defined as follows:
Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }.
Given M queries, your program must output the results of these queries.
Input
- The first line of the input file contains the integer N.
- In the second line, N numbers follow.
- The third line contains the integer M.
- M lines follow, where line i contains 2 numbers xi and yi.
Output
Your program should output the results of the M queries, one query per line.
Example
Input:
3
-1 2 3
1
1 2
Output:
2
解题思路:这一题。。。我是真不会,就找了别人的题解学习了一下,然后又被线段树强大的力量给震撼到了。。
这种类似于分治的思想我一直不能很好的掌握。。。
题目大意就是给你一段序列每次查需(l,r)内最大的连续区间和。
对于一个区间的最大连续和它可能出现的位置,前缀 后缀 或者从中间向两边拓展
所以对于每一个节点我们维护他的
ls:从左端点开始的最大连续和
rs 以右端点结束的最大连续和
ms:整个区间的最大连续和
s:区间和。
至于为什么要维护一个区间和,其实也是为了转移方便。
对于一个父节点它的ls 能够更新位左子区间的和加上右子区间的ls。
下面说明如何合并两个区间。
ls :max (lson.ls,lson.s+rson.ls);
rs :max(rson.rs,rson.s+lson.rs);
ms:max( max(lson.ms,rson.ms),lson.rs+rson.ls);//这里是因为最大连续和可能出现在从中间到两边拓展的情况。
以上是合并两个区间。。
下面是如何查询。
如何合并区间容易想到。。可能我对于递归还不是太了解,解决了区间合并却不知道要如何去查询。
对于我们要查询的区间我们可以把它分为2种情况。
当前节点完全等于查询的区间&