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 <bits/stdc++.h>
using namespace std;
const int maxn = 5e4+3;
int a[maxn]={0}, vis[maxn<<1], b[750][750];
vector<int>v[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<l; ++i)
        {
            int pos = lower_bound(v[a[i]].begin(), v[a[i]].end(), y) - v[a[i]].begin()-1;
            if(pos < 0) continue;
            ans = max(ans, v[a[i]][pos] - i);
        }
        for(int i=y; 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值