跳到正文

题解

题解:P13981 数列分块入门 6

gmb729约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年10月27日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟
题目
P13981

版本

  1. v2当前
  2. v1

一种新型写法…

正言


我们先打暴力。

单点插入时我们考虑新建一个节点,用链表维护,询问第 xx 个数时,我们从 1 开始,往后跳 xx 个数输出。

然后在考虑优化。

我们发现,新增加的节点最多为 nn 个,所以最终序列的个数一定在 O(n)O(n) 的级别。

因此,我们设 kk 为 n\sqrt n ,再维护第 k,2k,…,k×kk,2k,\dots,k\times k 的位置,每增加节点使得总结点数为 kk 的倍数,则加一个维护的位置。

查询时,我们先找到比 xx 小且最近的位置(刚刚维护的),再往后跳 x−x/k×kx-x/k\times k 个位置,输出。

时间复杂度为 O(nn)O(n\sqrt n)。

code


C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,a[1000005],qq,e[1000005],uu,h[1000005],q[1000005],t,op,l,r,c;
int find(int x){
	int r=e[x/uu];
	x-=x/uu*uu;
	while(x--)r=h[r];
	return r;
}
signed main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n;qq=n;uu=sqrt(n);
	h[0]=1;
	for(int i=1;i<=n;i++){
		cin>>a[i],q[i]=i-1,h[i]=i+1;
		if(i%uu==0)e[++t]=i;
	}c=n;
	while(qq--){
		cin>>op;
		if(op==0){
			cin>>l>>r;
			int ll=l;ll=(ll+uu-1)/uu;
			l=find(l);
			h[q[l]]=++c;
			q[c]=q[l];
			q[l]=c;
			h[c]=l;
			a[c]=r;
			for(int i=ll;i<=t;i++)e[i]=q[e[i]];
			if(c%uu==0)e[++t]=n;
		}else{
			cin>>l;
			cout<<a[find(l)]<<"\n";
		}
	}
	return 0;
}
原文