CodeForces 622 C. Not Equal on a Segment(水~)

来源:互联网 发布:ios开发需要mac吗 编辑:程序博客网 时间:2024/05/21 02:49

Description
给出一个长度为n的序列,m次查询,每次查询询问区间[l,r]中是否存在不等于x的数,如果不存在则输出-1,存在则任意输出区间中任意一个不等于x的值
Input
第一行为两个整数n和m分别表示序列长度和查询次数,第二行为n个整数ai表示该序列,之后m行每行三个整数li,ri,xi表示一次查询(1<=n,m<=2*10^5,1<=ai<=10^6,1<=li<=ri<=n,1<=xi<=10^6)
Output
对于每次查询,如果区间[li,ri]中存在不等于xi的数则任意输出一个,否则输出-1
Sample Input
6 4
1 2 1 1 3 5
1 4 1
2 6 2
3 4 1
3 4 2
Sample Output
2
6
-1
4
Solution
简单题,每次直接暴力枚举会超时,但是如果把数值相同的连续子串合并就可以了
Code

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define maxn 222222int n,m,a[maxn],pos[maxn];struct node{    int l,r,v;}p[maxn];int main(){    while(~scanf("%d%d",&n,&m))    {        int l,r,x,res;        for(int i=1;i<=n;i++)            scanf("%d",&a[i]);        res=0,l=1;        for(;l<=n;l++)        {            r=l;            while(r<=n&&a[l]==a[r])r++;            if(r==n+1)r=n;            else if(a[l]!=a[r])r--;            for(int i=l;i<=r;i++)pos[i]=res;            p[res].l=l,p[res].r=r,p[res++].v=a[l];            l=r;        }        while(m--)        {            scanf("%d%d%d",&l,&r,&x);            int flag=0;            for(int i=pos[l];i<res;i++)            {                if(p[i].r<l)continue;                if(p[i].l>r)break;                if(p[i].v!=x)                {                    if(p[i].r<=r)printf("%d\n",p[i].r);                    else if(p[i].l>=l)printf("%d\n",p[i].l);                    else printf("%d\n",r);                    flag=1;                    break;                }            }            if(!flag)printf("-1\n");        }    }    return 0;}
0 0
原创粉丝点击