数列找不同

本文介绍了一种基于离线查询的算法实现,通过预处理和区间划分的方法来高效地解决数列中元素唯一性的批量查询问题。该算法适用于大量查询场景,能够在预处理阶段将数列进行分块,从而在查询阶段快速判断给定区间的元素是否各不相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
现有数列A_1,A_2,\cdots,A_NA
1
​ ,A
2
​ ,⋯,A
N
​ ,Q 个询问(L_i,R_i)(L
i
​ ,R
i
​ ),A_{Li} ,A_{Li+1},\cdots,A_{Ri}A
Li
​ ,A
Li+1
​ ,⋯,A
Ri
​ 是否互不相同

输入格式
第1 行,2 个整数N,QN,Q

第2 行,N 个整数A_{Li} ,A_{Li+1},\cdots,A_{Ri}A
Li
​ ,A
Li+1
​ ,⋯,A
Ri

Q 行,每行2 个整数L_i,R_iL
i
​ ,R
i

输出格式
对每个询问输出一行,“Yes” 或者“No”

输入输出样例
输入 #1 复制
4 2
1 2 3 2
1 3
2 4
输出 #1 复制
Yes
No
说明/提示
• 对于50% 的数据,N,Q \le 10^3N,Q≤10
3

• 对于100% 的数据,1 \le N,Q \le 10^5, 1 \le A_i \le N, 1 \le L_i \le R_i \le N1≤N,Q≤10
5
,1≤A
i
​ ≤N,1≤L
i
​ ≤R
i
​ ≤N

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

const int maxn=100010;

inline int read(){
    int s=0,w=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
    	if(ch=='-'){
    		w=-1;
    	}
    	ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
    	s=s*10+ch-'0';
    	ch=getchar();
    }
    return s*w;
}

int n,m,hhh,ans=0,kkksc03,kkksc04,cnt[maxn],a[maxn],i;

bool anb[maxn];

struct node{
    int l,r,p;
}q[maxn];

bool cmp(const node x,const node y){
    return (x.l/hhh)==(y.l/hhh)?x.r<y.r:x.l<y.l;
}

void add(int position){
    if((++cnt[a[position]])==1){
		++ans;
	}
}

void remove(int position){
    if((--cnt[a[position]])==0){
		--ans;
	}
}

int main(){
	n=read();
	m=read();
	hhh=sqrt(n);
	for(i=1;i<=n;i++){
		a[i]=read();
	}
    for(i=1;i<=m;i++){
        q[i].l=read();
        q[i].r=read();
        q[i].p=i;
    }
    sort(q+1,q+1+m,cmp);
    for(i=1;i<=m;i++){
        int L=q[i].l,R=q[i].r;
        while(kkksc03<L){
			remove(kkksc03++);
		}
        while(kkksc03>L){
			add(--kkksc03);
		}
        while(kkksc04<R){
			add(++kkksc04);
		}
        while(kkksc04>R){
			remove(kkksc04--);
		}
        if(ans==(R-L+1)){
        	anb[q[i].p]=1;
        }
    }
    for(i=1;i<=m;i++){
        if(anb[i]==1){
        	printf("Yes\n");
        }
        else{
        	printf("No\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值