SPOJ:Zero Query(分块 & 二分)

Given an array having N elements, each element is either -1 or 1.

You have M queries, each query has two numbers L and R, you have to answer the length of the longest subarray in range L to R (inclusive) that its sum is equal to 0.

Input

The first line contains two numbers N and M (1 <= NM <= 50000) - the number of elements and the number of queries.

The second line contains N numbers - the elements of the array, each element is either -1 or 1.

In the next M lines, each line contains two numbers L and R (1 <= L <= R <= N).

Output

For each query, print the length of the longest subarray that satisfies the query in one line. If there isn't any such subarray, print 0.

Note

Subarray in an array is like substring in a string, i.e. subarray should contain contiguous elements.

Example

Input:
6 4
1 1 1 -1 -1 -1
1 3
1 4
1 5
1 6
Output:
0
2
4
6
题意:给N个数字,范围在[-1,1],Q个询问,求出指定区间内和为0的最长的子区间。

思路:分块 + 二分。

# include 
using namespace std;
const int maxn = 5e4+3;
int a[maxn]={0}, vis[maxn<<1], b[750][750];
vectorv[maxn<<1];
int main()
{
    int n, m, x, y;
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; ++i) scanf("%d",&a[i]), a[i] += a[i-1];
    for(int i=0; i<=n; ++i) a[i] += 50003, v[a[i]].push_back(i);;
    int len = 70;
    int num = (n+len)/len;
    for(int i=0; i<=n; i+=len)
    {
        int imax = 0;
        memset(vis, -1, sizeof(vis));
        for(int j=i; j<=n; ++j)
        {
            if(j%len == 0) b[i/len][j/len] = imax;
            if(vis[a[j]] == -1) vis[a[j]] = j;
            else imax = max(imax, j-vis[a[j]]);
        }
        b[i/len][num] = imax;
    }
    while(m--)
    {
        scanf("%d%d",&x,&y);
        --x;
        int l = (x+len)/len*len;
        int r = y/len*len;
        int ans = b[l/len][r/len];
        for(int i=x; i=r; --i)
        {
            int pos = lower_bound(v[a[i]].begin(), v[a[i]].end(), x) - v[a[i]].begin();
            if(pos == v[a[i]].size()) continue;
            ans = max(ans, i-v[a[i]][pos]);
        }
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(二分/三分)