Sequence and Queries 0

For each query range [i,j] of a ±1 sequence, report the length of the longest contiguous subarray inside it whose sum is 0, or 0 if none exists.

Hard9Segment treePrefix sumDivide and conquerDynamic programmingNo attempts yetTime limit2.5sMemory limit512 MB

Problem

You are given a sequence A1,A2,,ANA_1, A_2, \dots, A_N of length NN in which every element is 11 or 1-1. Write a program that answers the following query.

  • i j: among the contiguous subsequences contained in Ai,Ai+1,,AjA_i, A_{i+1}, \dots, A_j, take those whose elements sum to 00 and print the length of the longest one. Print 00 if no contiguous subsequence sums to 00.

Input

The first line contains the size of the sequence NN (1N1000001 \le N \le 100\,000).

The second line contains A1,A2,,ANA_1, A_2, \dots, A_N separated by spaces. (AiA_i is 11 or 1-1)

The third line contains the number of queries MM (1M1000001 \le M \le 100\,000).

Each of the next MM lines holds one query, given as two integers ii and jj (1ijN1 \le i \le j \le N).

Output

Print the answer to each query on its own line, in the order the queries are given.