Problem Description
GTY has n gay friends. To manage them conveniently, every morning he ordered all his gay friends to stand in a line. Every gay friend has a characteristic value ai , to express how manly or how girlish he is. You, as GTY’s assistant, have to answer GTY’s queries. In each of GTY’s queries, GTY will give you a range [l,r] . Because of GTY’s strange hobbies, he wants there is a permutation [1…r−l+1] in [l,r]. You need to let him know if there is such a permutation or not.
Input
Multi test cases (about 3) . The first line contains two integers n and m ( 1≤n,m≤1000000 ), indicating the number of GTY’s gay friends and the number of GTY’s queries. the second line contains n numbers seperated by spaces. The ith number ai ( 1≤ai≤n ) indicates GTY’s ith gay friend’s characteristic value. The next m lines describe GTY’s queries. In each line there are two numbers l and r seperated by spaces ( 1≤l≤r≤n ), indicating the query range.
Output
For each query, if there is a permutation [1…r−l+1] in [l,r], print ‘YES’, else print ‘NO’.
题意:
给定长度为n的序列,m个询问
每个询问:
问区间[l,r]中的数是否是1-(r-l+1)的一个排列(全排列中的一种)
思路:
是排列的充要条件:
- [l,r]的区间和 与 1~(r-l+1)的和相同
- 区间内每个数只出现一次
条件1很简单,区间和用前缀和解决就行了,
条件2解决方法:
last[i]表示a[i]上一次出现的位置,
然后建线段树维护last的区间最大值,[l,r]的last最大值即
区间中每个数上一次出现的位置最接近区间右端点的位置
如果最大值小于左端点L,则说明区间中每个数只出现了一次
code:
#include<cstring>
#include<iostream>
using namespace std;
const int maxm=1e6+5;
int last[maxm];
int pos[maxm];
int a[maxm<<2];
int sum[maxm];
int n,m;
void build(int l,int r,int node){
if(l==r){
a[node]=last[l];
return ;
}
int mid=(l+r)/2;
build(l,mid,node*2);
build(mid+1,r,node*2+1);
a[node]=max(a[node*2],a[node*2+1]);
}
int ask(int st,int ed,int l,int r,int node){
if(st<=l&&ed>=r){
return a[node];
}
int mid=(l+r)/2;
int ans=0;
if(st<=mid){
ans=max(ans,ask(st,ed,l,mid,node*2));
}
if(ed>=mid+1){
ans=max(ans,ask(st,ed,mid+1,r,node*2+1));
}
return ans;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
for(int i=1;i<=n;i++){
pos[i]=0;
}
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
sum[i]=sum[i-1]+x;
last[i]=pos[x];
pos[x]=i;
}
build(1,n,1);
while(m--){
int l,r;
scanf("%d%d",&l,&r);
int len=(r-l+1);
if(sum[r]-sum[l-1]!=len*(len+1)/2){
puts("NO");
}else{
int ans=ask(l,r,1,n,1);
if(ans<l){
puts("YES");
}else{
puts("NO");
}
}
}
}
return 0;
}