Loi_Vampire's Blog

自己选择的路,就算跪着也要走完

01/25
11:31
数据结构 线段树

SPOJ 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

题意:给定一个序列,每次询问一个区间的最大连续子段和。

线段树,维护左起最大连续子段和,右起最大连续子段和,最大连续子段和,以及区间和。

在询问时,一共有三种情况: Ⅰ 最大连续子段和在左区间,直接递归查询 Ⅱ 最大连续子段和在右区间,同上 Ⅲ 最大连续子段和跨越左右区间,那么,对左区间最大连续子段和,右区间最大连续子段和,和左区间右起最大连续子段和 右区间左起最大连续子段和的和 取max即可