给一列数,每次查询一个区间,求出这个区间中,从右到左第一个出现两次的数。
首先预处理一下每个数左边离他最近的相同的数的位置,读完数据后,按查询的右区间递增排
个序,然后一个一个添加。添加到a[i]时,若l[i]不为0,那么对于右区间为i,左区间为1...l[i]的查询,答案就是i,这里可以用线段树成段赋值处理,要注意的一点是,每次记录一下上一次添加时的l[i]为last,如果本次的l[i]<=last的话,这个l[i]是肯定不会是答案的,因为1...last的答案已经有一个更靠右的值了....
刚开始背题意误导,想着从右往左去更新,并且使得每个位置只被覆盖一次,然后写着写着就挂了...其实从前先后更新的话根本就不用考虑覆盖几次的问题...后面的值直接覆盖前面的值就是要的答案...
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#define lson id<<1,l,m
#define rson id<<1|1,m+1,r
#include <map>
using namespace std;
typedef long long ll;
const int maxn=851000;
struct segment
{
int dt[maxn<<2];
int st[maxn<<2];
void init()
{
memset(dt,0,sizeof dt);
memset(st,0,sizeof st);
}
void pushup(int id)
{
if (dt[id<<1]==dt[id<<1|1]) dt[id]=dt[id<<1];
else dt[id]=0;
}
void pushdown(int id)
{
if (st[id])
{
st[id<<1]=st[id<<1|1]=st[id];
dt[id]=st[id];
st[id]=0;
}
}
void modify(int L,int R,int c,int id,int l,int r)
{
pushdown(id);
if (L==l && R==r)
{
st[id]=c;
return;
}
int m=(l+r)>>1;
if (R<=m) modify(L,R,c,lson);
else if (L>m) modify(L,R,c,rson);
else
{
modify(L,m,c,lson);
modify(m+1,R,c,rson);
}
pushup(id);
}
int query(int pos,int id,int l,int r)
{
pushdown(id);
int m=(l+r)>>1;
if (l==r) return dt[id];
if (pos<=m) return query(pos,lson);
else return query(pos,rson);
}
}sgt;
struct node
{
int l,r;
int id;
bool operator<(const node &p)const
{
if (r != p.r) return r<p.r;
else return l<p.l;
}
}qy[66666];
int ans[maxn];
int a[maxn],b[maxn],c[maxn];
int l[maxn];
int ps[maxn];
int n,m;
int main()
{
// freopen("in.txt","r",stdin);
while(~scanf("%d",&n))
{
for (int i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
memcpy(b,a,sizeof a);
memcpy(c,a,sizeof a);
memset(ans,0,sizeof ans);
sort(b,b+n);
int size=unique(b,b+n)-b;
for (int i=0; i<n; i++)
{
int t=lower_bound(b,b+size,a[i])-b+1;
a[i]=t;
}
memset(ps,0,sizeof ps);
memset(l,0,sizeof l);
for (int i=0; i<n; i++)
{
if (ps[a[i]]) l[i]=ps[a[i]];
ps[a[i]]=i+1;
}
scanf("%d",&m);
for (int i=0; i<m; i++)
{
scanf("%d%d",&qy[i].l,&qy[i].r);
qy[i].id=i;
}
sort(qy,qy+m);
int pos=0;
sgt.init();
int last=0;
for (int k=0; k<n; k++)
{
if (l[k] && l[k]>last)
{
sgt.modify(1,l[k],l[k],1,1,n);
last=l[k];
}
while(qy[pos].r==k+1)
{
ans[qy[pos].id]=sgt.query(qy[pos].l,1,1,n);
pos++;
}
}
for (int i=0; i<m; i++)
if(ans[i]) cout<<c[ans[i]-1]<<endl;
else cout<<"OK"<<endl;
cout<<endl;
}
return 0;
}