Eugeny and Array

Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:

  • Query number i is given as a pair of integers liri (1 ≤ li ≤ ri ≤ n).
  • The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.

Help Eugeny, answer all his queries.


Input

The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).

Output

Print m integers — the responses to Eugene's queries in the order they occur in the input.


Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0


解题思路:

因为题目说序列可以随意排列,所以不用考虑各个-1和1的位置,因此首先统计-1和1的个数,然后计算出区间长度,如果区间长度为奇数(eg:-1 -1 1or 1 1 -1),则一定不会等于零,所以,这种情况只能输出1;接下来考虑区间长度为偶数的情况,假想:如果-1的个数和1的个数都大于区间长度的一半,那么和相加一定能等于0,所以,方便起见,只需找出-1的个数与1的个数中较小的那一个,然后看其是否大于等于区间长度的一半即可,若大于等于,则输出1,否则,输出0;


源码:

1)没用数组;

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int n,m,x;
    int num1=0,num2=0;
    while(cin>>n>>m)
    {
        for(int i=0;i<n;i++)
        {
            cin>>x;
            if(x<0) num1++;
            else num2++;
        }
        while(m--)
        {
            int l,r;
            int jet;
            cin>>l>>r;
            jet=r-l+1;
            if(jet%2==1)
                cout<<'0'<<endl;
            else
            {
                if(min(num1,num2)>=jet/2)//or if(num1>=jet/2&&num2>=jet/2)
                    cout<<'1'<<endl;
                else
                    cout<<'0'<<endl;
            }
        }
    }
    return 0;
}

2)用数组

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

int a[200005];
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int ponum = 0,nanum = 0;
        int x=0,y=0;
        for(int i=1; i<=n; ++i)
        {
            scanf("%d",&a[i]);
            if(a[i]==-1)nanum++;
            if(a[i]==1) ponum++;
        }
        int flag = min(nanum,ponum);
        for(int i=1; i<=m; ++i)
        {
            scanf("%d%d",&x,&y);
            int t = y-x+1;
            if(t%2==1)
                printf("0\n");
            else if(t<=2*flag)
                printf("1\n");
            else
                printf("0\n");
        }
    }
    return 0;
}

阅读更多
版权声明: https://blog.csdn.net/qq_40829288/article/details/80344545
个人分类: OJ ACM
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭