3339: Rmq Problem
Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 958 Solved: 482
[ Submit][ Status][ Discuss]
Description
Input
Output
Sample Input
0 2 1 0 1 3 2
1 3
2 3
1 4
3 6
2 7
Sample Output
0
3
2
4
HINT
解题思路:离线操作,先求出[1,i]的答案,并且记录下当前i的next[i]表示下个和i相同的点的位置,
然后就发现当要求l+1的时候,只需要更新a[l]的影响,于是,只需要将[i,next[i]-1]]这段区间进行
更新就行了,查询就是查询点。(线段树维护)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int n,q,mex,len,lg,rg,ans;
int next[210000],pre[210000],a[210000],f[210000];
int mi[840000],nex[210000];
int h[210000],to[210000],bian[210000];
int size[210000],ang[210000];
inline int read()
{
char y; int x=0,f=1; y=getchar();
while (y<'0' || y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0' && y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
}
void insert(int x,int y,int now)
{
++len; to[len]=y; bian[len]=now; next[len]=h[x]; h[x]=len;
}
void change(int now,int l,int r,int zhi)
{
if (lg<=l && r<=rg)
{
mi[now]=min(mi[now],zhi);
return;
}
int mid=(l+r)/2;
if (lg<=mid) change(now*2,l,mid,zhi);
if (mid+1<=rg) change(now*2+1,mid+1,r,zhi);
}
void query(int now,int l,int r)
{
ans=min(ans,mi[now]);
if (l==r) return;
int mid=(l+r)/2;
if (lg<=mid) query(now*2,l,mid);
if (mid+1<=rg) query(now*2+1,mid+1,r);
}
int main()
{
n=read(); q=read(); mex=0;
for (int i=1;i<=n;++i)
{
int x=read(); ++size[x]; a[i]=x;
if (size[x]>1) nex[pre[x]]=i;
pre[x]=i;
while (size[mex]>0) ++mex;
f[i]=mex;
}
for (int i=1;i<=q;++i)
{
int l,r; l=read(); r=read();
insert(l,r,i);
}
memset(mi,0x7f,sizeof(mi));
for (int i=1;i<=n;++i)
{
int u=h[i];
while (u!=0)
{
lg=to[u]; rg=to[u];
ans=f[lg];
query(1,1,n);
ang[bian[u]]=ans;
u=next[u];
}
lg=i+1;
if (nex[i]==0) rg=n; else rg=nex[i]-1;
change(1,1,n,a[i]);
}
for (int i=1;i<=q;++i)
printf("%d\n",ang[i]);
}