【LOJ#6282】数列分块6

题目大意:给定一个由 N 个数组成的序列,维护两种操作:单点询问,单点插入。N < 100000

题解:在块内维护一个链表,支持动态插入数字,同时对于非随即数据来说,若块的大小过大,需要重构。

注:对于 C++ vector 的 insert 函数的含义是在给定迭代器的后面插入数值。

代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;

inline int read(){
    int x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}

int n,q,st[maxn],top,tot;
struct node{int l,r;vector<int> v;}b[1000];

void make_block(){
	tot=(int)sqrt(n);
	for(int i=1;i<=tot;i++)b[i].l=(i-1)*tot+1,b[i].r=i*tot;
	if(b[tot].r<n)++tot,b[tot].l=b[tot-1].r+1,b[tot].r=n;
	for(int i=1;i<=tot;i++)
		for(int j=b[i].l;j<=b[i].r;j++)
			b[i].v.push_back(st[j]);
}

void read_and_parse(){
	n=read(),top=q=n;
	for(int i=1;i<=n;i++)st[i]=read();
	make_block();
}

inline pair<int,int> query(int pos){//返回这个位置所在的块链表的位置
	int idx=1;
	while(pos>b[idx].v.size())pos-=b[idx].v.size(),++idx;
	return make_pair(idx,pos-1);//vector下标从 0 开始
}

void rebuild(){
	top=0;
	for(int i=1;i<=tot;i++){
		for(int j=0;j<b[i].v.size();j++)st[++top]=b[i].v[j];
		b[i].v.clear();
	}
	n=top;make_block();
}

void insert(int pos,int val){
	pair<int,int> t=query(pos);
	b[t.first].v.insert(b[t.first].v.begin()+t.second,val);
	if(b[t.first].v.size()>20*tot)rebuild();
}

void solve(){
	int opt,l,r,val;
	while(q--){
		opt=read(),l=read(),r=read(),val=read();
		if(opt==0)insert(l,r);
		else{
			pair<int,int> t=query(r);
			printf("%d
",b[t.first].v[t.second]);
		}
	}
}

int main(){
	read_and_parse();
	solve();
	return 0;
}
原文地址:https://www.cnblogs.com/wzj-xhjbk/p/9971939.html